Wednesday, April 13, 2011

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?

From stackoverflow
  • 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);
    
    alex2k8 : Your code actually returned 'null' container, but with such code: ContentPresenter container = FindVisualChild(item); I got the "foo" element. Thanks!

0 comments:

Post a Comment