【WPF】树形结构TreeView的用法(MVVM)(转)
【WPF】树形结构TreeView的用法(MVVM)
TreeView控件的用法还是有蛮多坑点的,最好记录一下。
参考项目:
静态的树形结构
如果树形结构的所有子节点都已经确定且不会改动,可以直接在控制层用C#代码来生成这个TreeView。
var rootItem = new OutlineTreeData { outlineTypeName = "David Weatherbeam", Children= { new OutlineTreeData { outlineTypeName="Alberto Weatherbeam", Children= { new OutlineTreeData { outlineTypeName="Zena Hairmonger", Children= { new OutlineTreeData { outlineTypeName="Sarah Applifunk", } } },new OutlineTreeData { outlineTypeName="Jenny van Machoqueen", Children= { new OutlineTreeData { outlineTypeName="Nick van Machoqueen", }, new OutlineTreeData { outlineTypeName="Matilda Porcupinicus", }, new OutlineTreeData { outlineTypeName="Bronco van Machoqueen", } } } } }, new OutlineTreeData { outlineTypeName="Komrade Winkleford", Children= { new OutlineTreeData { outlineTypeName="Maurice Winkleford", Children= { new OutlineTreeData { outlineTypeName="Divinity W. Llamafoot", } } }, new OutlineTreeData { outlineTypeName="Komrade Winkleford, Jr.", Children= { new OutlineTreeData { outlineTypeName="Saratoga Z. Crankentoe", }, new OutlineTreeData { outlineTypeName="Excaliber Winkleford", } } } } } } };
运行后能看到树形结构是下面的样子。
获取TreeViewItem控件
前台页面xaml:
<!-- 树形结构 --> <TreeView x:Name="treeView" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,-10,0,0" ItemsSource="{Binding ItemTreeDataList}" BorderThickness="0" Width="215" Height="210"> <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" /> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> <Setter Property="FontWeight" Value="Normal" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="FontWeight" Value="Bold" /> </Trigger> </Style.Triggers> </Style> </TreeView.ItemContainerStyle> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Children}"> <TextBlock x:Name="treeViewItemTB" Text="{Binding itemName}" Tag="{Binding itemId}"/> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView>
尝试过在初始化时获取TreeViewItem,发现都是为Null。
- TreeViewItem item= (TreeViewItem)(myWindow.treeView.ItemContainerGenerator.ContainerFromIndex(0)); // 无法获取,为Null!
- VisualTreeHelper.GetChild(); // 无法获取,为Null!
谷歌一下,看到这篇解答,下面这位跟我遇到的情况一样,用以上方法都无法获取TreeViewItem。