Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
alex2k8 Avatar asked Dec 06 '25 17:12

alex2k8


1 Answers

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);
like image 174
Arcturus Avatar answered Dec 08 '25 07:12

Arcturus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!