Brandon
Brandon

Reputation: 3266

WPF Listbox Virtualization - How to Bring Item Into View

I've got a listbox where I have to have virtualization on. I then have a map that has items plotted on it that need to have the feature of letting the user click on them. When they click on an item, I need to bring that item into view in the listbox.

The issue is virtualization. When I try to grab the container, it returns null, which makes sense, however what's the right thing to do? I've tried a few things such as UpdateLayout(), but I've yet to find the answer. Any ideas?

var container = lstItems.ItemContainerGenerator.ContainerFromItem(clickedItem);
if (container != null)
{
     var exp = container.Descendants().OfType<Expander>().FirstOrDefault();
     if (exp != null)
     {
          exp.IsExpanded = true;
          exp.BringIntoView();
     }
}

Upvotes: 0

Views: 1224

Answers (1)

Mike Strobel
Mike Strobel

Reputation: 25623

ListBox gives you a method to do exactly this:

lstItems.ScrollIntoView(clickedItem);

If you insert that line above the code you've already shown, then container should give you an actual ListBoxItem.

However, if the item was out of view, the template probably hasn't been applied. You can get around this by calling container.UpdateLayout() before searching for the Expander.

You'll still need the exp.BringIntoView() call, though, as the expander will presumably become larger once it's expanded, and the initial call to ScrollIntoView may not have brought it far enough into the viewport. Alternatively, you could just call ScrollIntoView a second time.

Upvotes: 4

Related Questions