代码之家  ›  专栏  ›  技术社区  ›  Moonshield

数据绑定后的WPF TreeViewItem头值

  •  1
  • Moonshield  · 技术社区  · 16 年前

    我有一个TreeView,它的内容(嵌套的TreeViewItems)是通过数据绑定从一个数据集生成的,看起来一切都很好。我遇到的问题是,当我尝试在代码中操作TreeViewItem头的内容时,Header属性返回TreeViewItem是从中生成的DataRowView,而不是像我期望的那样,返回由模板生成的控件。

        <DataTemplate x:Key="seasonTreeViewItemTemplate">
            <TreeViewItem>
                <TreeViewItem.Header>
                    <CheckBox Content="{Binding Path=Row.SeasonID}" Tag="{Binding}" ToolTip="{Binding Path=Row.Title}" IsEnabled="{StaticResource seasonPermitted}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" />
                </TreeViewItem.Header>
    
                <TreeViewItem Header="Championships" ItemTemplate="{StaticResource championshipTreeViewItemTemplate}">
                    <TreeViewItem.ItemsSource>
                        <Binding Path="Row" ConverterParameter="FK_Championship_Season">
                            <Binding.Converter>
                                <local:RowChildrenConverter />
                            </Binding.Converter>
                        </Binding>
                    </TreeViewItem.ItemsSource>
                </TreeViewItem>
            </TreeViewItem>
        </DataTemplate>
    

    有谁能指出我的错误所在并建议我如何访问头复选框(如果可能的话,最好不要深入VisualTree)?

    谢谢, 詹姆斯

    1 回复  |  直到 16 年前
        1
  •  1
  •   Moonshield    15 年前

    好吧,经过一番调查,我找到了解决这个问题的适当办法。

    使用以下代码,可以在模板中找到命名项:

    if (treeViewItem != null)
    {
            //Get the header content presenter.
            ContentPresenter header = treeViewItem.Template.FindName("PART_Header", treeViewItem) as ContentPresenter;
    
            if (header != null)
            {
                //Find a CheckBox called "checkBoxName"
                CheckBox cb = treeViewItem.HeaderTemplate.FindName("checkBoxName", header) as CheckBox;
            }
    } 
    

    <HierarchicalDataTemplate x:Key="templateName" ItemsSource="{Binding Path=someCollection}" ItemTemplate="{StaticResource someOtherTemplate}">
        <TextBlock Text="{Binding Path=SomeProperty}" />
    </HierarchicalDataTemplate>
    

    我希望其他人会发现这些信息有用。

    推荐文章