首页 > 解决方案 > 如何递归地遍历 TreeView-items

问题描述

我对 WPF 很陌生,我正在尝试编写某种资源管理器,因此我需要创建一个自定义的Microsoft.Xaml.Behaviors.Behavior.

为了自动展开并选择合适TreeViewItem的s,我需要遍历所有DataContexts的对应项。

可悲的是,使用的常见建议ItemsControl.ItemContainerGenerator.ContainerFrom[...]有一个很大的缺点:它只为TreeViewItem已经绘制的 s 提供结果。

即使框架基本上知道如何通过下面发布的 XAML 代码获取ItemsSource每种类型的.DataContextItemsSourceDataContext

<TreeView ItemsSource="{Binding Items}">
   <TreeView.Resources>

       <DataTemplate DataType="{x:Type local:classA}" >
           <TextBlock Text="{Binding name}" Foreground="Blue" />
       </DataTemplate>

       <HierarchicalDataTemplate DataType="{x:Type local:classB}" ItemsSource="{Binding subItems}" >
           <TextBlock Text="{Binding name}" Foreground="Green" />
       </HierarchicalDataTemplate>

       <HierarchicalDataTemplate DataType="{x:Type local:classC}" ItemsSource="{Binding subItems}" >
           <TextBlock Text="{Binding name}" Foreground="Red" />
       </HierarchicalDataTemplate>

   </TreeView.Resources>
</TreeView>

https://stackoverflow.com/a/35565892

所以,在这个例子中,框架实际上应该知道如何根据我的代码从classB- 和 -类型的实例中获取子项。我正在寻找的是基于在.classCxamlHierarchicalDataTemplatexaml

标签: c#wpfxamltreeviewhierarchicaldatatemplate

解决方案


推荐阅读