WPF的Treeview子节点绑定
程序员文章站
2022-06-08 14:02:35
...
WPF的Treeview子节点绑定
做法使用HierarchicalDataTemplate 更改DataType。当前ViewModel下有个ObservableCollection类型的EcgProjectList,于是一级节点都是EcgProject类型,EcgProject下有个ObservableCollection类型的Sheets,于是二级节点是EcgSheet类型。如果还想要三级节点,就在EcgSheet下定义一个T的集合X,然后前端 加个ItemsSource绑定X。然后再加个HierarchicalDataTemplate,DataType为T。第四第五等等以此类推。
<TreeView x:Name="treeView" ItemsSource="{Binding EcgProjectList}" Cursor="Hand" Background="{DynamicResource ProjectListColor}" BorderThickness="0,0,0,1" Margin="5,79,10,0" MouseLeftButtonUp="treeView_MouseLeftButtonDown" SelectedItemChanged="Sheet_SelectedItemChanged" Height="282" VerticalAlignment="Top">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type Model:EcgProject}" ItemsSource="{Binding Sheets, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
<StackPanel Orientation="Horizontal" Margin="0,2,0,2">
<TextBlock FontSize="14" Height="20" VerticalAlignment="Center" Foreground="White" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ToolTip="{Binding Name, Mode=TwoWay}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type Model:EcgSheet}">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="14" Height="20" VerticalAlignment="Center" Foreground="White" Text="{Binding Name, Mode=OneTime}" ToolTip="{Binding Name, Mode=TwoWay}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
<TreeView.ContextMenu>
<ContextMenu>
<MenuItem Header="删除" IsCheckable="True" x:Name="DeleteTreeViewNode" Click="DeleteTreeViewNode_Click">
</ContextMenu>
</TreeView.ContextMenu>
</TreeView>
上述代码还写了treeview的菜单栏的相关代码