wpftreeviewitemtemplatefindname

Find ItemTemplate control in TreeView


My tree definition is:

<TreeView Name="tree" ItemsSource="{Binding Children}" >
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <CheckBox Name="foo"></CheckBox>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

Having a TreeViewItem element, I try to find corresponding CheckBox, but

tree.Template.FindName("foo", item);

throws

[System.InvalidOperationException] = {"This operation is valid only on elements that have this template applied."}

And

item.Template.FindName("foo", item)

gives me null. What is a right solution?


Solution

  • Try the x:Name property, instead of the Name property...

    Secondly, you need to reference the ItemTemplate, not the Template of the TreeView

    Also the second parameter must be the container of the ListItem, not the data item:

    ContentPresenter container = (ContentPresenter) tree.ItemContainerGenerator.ContainerFromItem(item);
    CheckBox box = (CheckBox) container.ContentTemplate.FindName("Foo", container);