【问题标题】:Find ItemTemplate control in TreeView在 TreeView 中查找 ItemTemplate 控件
【发布时间】:2010-10-13 03:23:14
【问题描述】:

我的树定义是:

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

有一个 TreeViewItem 元素,我试图找到对应的 CheckBox,但是

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

抛出

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

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

给我null。什么是正确的解决方案?

【问题讨论】:

    标签: wpf treeview itemtemplate findname


    【解决方案1】:

    试试 x:Name 属性,而不是 Name 属性...

    其次,需要引用ItemTemplate,而不是TreeView的Template

    另外第二个参数必须是ListItem的容器,而不是数据项:

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

    【讨论】:

    • 您的代码实际上返回了 'null' 容器,但是使用这样的代码: ContentPresenter container = FindVisualChild(item);我得到了“foo”元素。谢谢!
    • 有关 FindVisualChild 的更多详细信息,请参见 stackoverflow.com/questions/980120/…
    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2011-09-28
    相关资源
    最近更新 更多