I have looked here and here and many other places, but I just can't seem to get the ItemContainerGenerator.ContainerFromItem
method to work on a WPF TreeView! I have tried to pass in the actual item I want to see, but not getting anywhere with that, I just tried to get the first item in my TreeView. Here's my sample code:
private static bool ExpandAndSelectItem(ItemsControl parentContainer, object itemToSelect)
{
// This doesn't work.
parentContainer.BringIntoView();
// May be virtualized, bring into view and try again.
parentContainer.UpdateLayout();
parentContainer.ApplyTemplate();
TreeViewItem topItem = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(parentContainer.Items[0]);
// Can't find child container unless the parent node is Expanded once
if ((topItem != null) && !topItem.IsExpanded)
{
topItem.IsExpanded = true;
parentContainer.UpdateLayout();
}
}
As you can see, I have tried to call many "updating" methods to try to get the TreeView to be "visible" and "accessible". The Catch-22 seems to be that you can't use ContainerFromItem()
unless the first TreeViewItem is expanded, but I can't grab the TreeViewItem to Expand it until ContainerFromItem()
works!
Another funny thing that is happening is this: When I open this window (it is a UserControl), ContainerFromItem()
returns nulls, but if I close the window and open it back up, ContainerFromItem()
starts returning non-nulls. Is there any event I should be looking for or forcing to fire?