繁体   English   中英

如何将分层数据绑定到WPF TreeView?

[英]How to data bind a hierarchical data to a WPF TreeView?

类型如下:

class Category
{
    public string Name;
    public string Message;

    public ObservableCollection<Category> SubCategories;
}

它会说5个类别,其中每个类别包含0(无)到3之间的子类别。

我知道如何将非分层数据绑定到WPF TreeView,但无法弄清楚分层数据值。

这是一个例子......

<!-- Create a TreeView, and have it source data from
       the AnimalCategories collection -->
  <TreeView ItemsSource="{x:Static local:Window1.AnimalCategories}">

    <!-- Specify the template that will display a node
         from AnimalCategories.  I.e., one each for “Amphibians”
         and “Spiders” in this sample.  It will get its nested
         items from the "Animals" property of each item -->
    <TreeView.ItemTemplate>
      <HierarchicalDataTemplate ItemsSource="{Binding Path=Animals}">

        <!-- Display the AnimalCategory by showing it's Category string -->
        <TextBlock FontWeight="Bold" Text="{Binding Path=Category}" />

        <!-- Specify the nested template for the individual Animal items
             that are within the AnimalCategories.  E.g. “California Newt”, etc. -->
        <HierarchicalDataTemplate.ItemTemplate>
          <DataTemplate>
            <TextBlock Text="{Binding Path=Name}"/>
          </DataTemplate>
        </HierarchicalDataTemplate.ItemTemplate>

      </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
  </TreeView>

这段代码来自这里,你可能对阅读那篇文章更有帮助,我在想。

首先,您需要将所有这些字段转换为属性 - WPF数据绑定无法绑定到字段。 (然后,Muad'Dib的答案应该有效。)

我知道很久以前就问过这个问题....但是在MSDN上有一个非常好的例子可以扩展Muad'Dib的答案。

他们的XAML看起来像这样:

    <StackPanel x:Name="LayoutRoot" Background="White">
        <StackPanel.Resources>
            <HierarchicalDataTemplate x:Key="ChildTemplate" >
                <TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
            </HierarchicalDataTemplate>
            <HierarchicalDataTemplate x:Key="NameTemplate" ItemsSource="{Binding Path=ChildTopics}" ItemTemplate="{StaticResource ChildTemplate}">
                <TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
            </HierarchicalDataTemplate>
        </StackPanel.Resources>
        <TreeView Width="400"  Height="300" ItemsSource="{Binding}" ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
    </StackPanel>

我发现将两者结合起来对我来说很完美。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM