代码之家  ›  专栏  ›  技术社区  ›  Joan Venge

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

  •  6
  • Joan Venge  · 技术社区  · 14 年前

    类型如下:

    class Category
    {
        public string Name;
        public string Message;
    
        public ObservableCollection<Category> SubCategories;
    }
    

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

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

    3 回复  |  直到 14 年前
        1
  •  10
  •   vcsjones    11 年前

    下面是一个例子。。。。。

    <!-- 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 我想,读那篇文章也许对你更有帮助。

        2
  •  2
  •   Ian Griffiths    14 年前

    首先,您需要将所有这些字段转换为属性—WPF数据绑定无法绑定到字段。(然后,穆阿德·迪布的回答应该会起作用。)

        3
  •  2
  •   Walter    7 年前

    我知道这个问题很久以前就被问到了。。。。但是有一个很好的 example 在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>
    

    我发现把两者结合起来对我来说是完美的。

    推荐文章