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

前端之家收集整理的这篇文章主要介绍了c# – 如何将分层数据绑定到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>

这段代码来自here,对于你来说,阅读那篇文章可能会更有帮助,我在想.

猜你在找的C#相关文章