views:

1045

answers:

1

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?

A: 

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