0

In my WPF I have two TreeViews. One is classes, and one for testing data for some elements. Now what I'm trying to do is: when you double click on a node in a Class Tree, in a Elements Tree a corresponding node should expand and element inside should be selected. Tree looks like that:
-Main Node: -Elements #Name# : -element 1 -element 2 -element 3 -element 4 -Elements #Other Name# : -...
Each "Elements" is a TreeViewItem and each "element" is a text block, with a lot of experimental data.

I'm just iterating the tree, till I found "Elements" with appropriate name, then go through its Items("element") and then select it.
But there is a strange case: on the first run it successfully expand "Elements" i need but fails to select "element" inside with ItemContainerGenerator giving me NULL, though on any other run other then first it will work just fine inside that "Elements", no matter what I'm doing with the tree (Expanding, Collapsing, Taping to other tree). What could be wrong?

private void TestTreeSearchAndExpand(TreeViewItem SearchedItem, string IHeader, string pin-name)
    {
        if (SearchedItem != null)
        {
            if (SearchedItem.Name.ToString() == IHeader)
            {
                SearchedItem.IsExpanded = true;
                foreach(FrameworkElement x in SearchedItem.Items)
                {
                    if (x.Name == pinname)
                    {
                        TreeViewItem PContainer = SearchedItem.ItemContainerGenerator.ContainerFromItem(x) as TreeViewItem;
                        if (PContainer != null)
                        {
                            PContainer.BringIntoView();
                            PContainer.IsSelected = true;
                        }

                    }
                }
            }
            else
            {
                if (SearchedItem.HasItems)
                {
                    foreach (var item in SearchedItem.Items)
                    {
                        TreeViewItem tmp = item as TreeViewItem;
                        TestTreeSearchAndExpand(tmp, IHeader, pinname);
                    }
                }
            }
        }
    }
Deviyani Swami
  • 701
  • 5
  • 16
  • Possible duplicate of [ItemContainerGenerator.ContainerFromItem() returns null?](https://stackoverflow.com/questions/6713365/itemcontainergenerator-containerfromitem-returns-null) – Olivier Jacot-Descombes Jun 05 '19 at 13:22
  • Yea, but i`m not "only" get NULL but sometimes get NULL – Kiriki Roa Jun 05 '19 at 14:00
  • Because the TreeView is virtualized, i.e., actually only the visible visual elements might be existing. My advice is to work with binding instead. Create a view model and work only with the view model. The view then binds its properties (like `IsExpanded`, `IsSelected` or `Text`) to the viewmodel. – Olivier Jacot-Descombes Jun 05 '19 at 14:06

0 Answers0