0

I have a listbox in my application which loads a lot of objects, so I use async binding to its ItemsSource property not to block the UI.

My probleem is that I would like to scroll to the selected item when the ItemsSource, so the async binding, is loaded (with ListView.ScrollIntoView() method).

Do anyone know a solution for this? Or which event of the ListView should I use that occurs the right time for this purpose?

user2042930
  • 640
  • 1
  • 7
  • 14
  • Not sure if I understood, you want to scroll into the view the new items as they are being added? – Nemanja Banda Jun 30 '15 at 12:58
  • No, basically I would like to display the available fonts for a font type chooser. But loading the fonts are slow, so I do it in async using async binding ({Binding Source=FontFamilies, IsAsync=True}). But I know the selected font already, so it is set as the SelectedItem of the ListView. When the FontFamilies finally loads then the ListView will be loaded with font families and the choosed one is selected nicely. But if the choosed font is Tahoma then it is close to the end of the list and I would like to scroll to that to make my app more user-friendly. – user2042930 Jun 30 '15 at 13:16

2 Answers2

0

Maybe this would work... If you have ListView named myListView, you could check each time the items are changed, and scroll the selected item into the view.

myListView.ItemContainerGenerator.ItemsChanged += new ItemsChangedEventHandler(ItemContainerGenerator_ItemsChanged);

Event handler:

void ItemContainerGenerator_ItemsChanged(object sender, ItemsChangedEventArgs e)
{
    if (myListView.SelectedItem != null)
    {
        myListView.ScrollIntoView(myListView.SelectedItem);
    }
}
Nemanja Banda
  • 796
  • 2
  • 14
  • 23
  • Hi! Thanks for your answer! Well this event seems to be good, but the listview doesn't scroll to the selected item. I checked and the selected item is not null and I tried to use UpdateLayout() method on the listview before calling ScrollIntoView(). Well I am trying to get it work now.. – user2042930 Jun 30 '15 at 13:48
  • Not sure when and how you change the selection, but maybe try with the SelectionChanged event? EDIT: Didn't see that you posted the answer while I was writing this, that you have already tried it and it worked :) – Nemanja Banda Jun 30 '15 at 14:03
0

Ah I've found the solution! LisBox has an event called SelectionChanged. This event is fine for me, because the SelectedItem is set for my listbox by a binding and when the async list of fonts loads then this event will be fired since the selected item will be selected in UI.

If I call the ScrollIntoView() in this event then it works properly. And since I need this behaviour only when the font families are loaded I unsubscribe from this event immediately after I made the listbox scroll to the selected item.

user2042930
  • 640
  • 1
  • 7
  • 14