我在视图模型中找到了几个绑定IsSelected属性的示例。但是,这些都不涉及具有分层数据模板的TreeView。
My Hierachy就像这样
我希望能够在一个部件下选择多个VM_Part实例或多个VM_Steps。我的想法是,我可以拥有一个上下文菜单,并对所选项目执行各种命令
<Window x:Class="NameSpace1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Hipot_Sequence_Editor"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
Title="MainWindow" Height="677.538" Width="896.456">
<Window.DataContext>
<local:VM_Main></local:VM_Main>
</Window.DataContext>
<Grid>
<TreeView x:Name="treeView" Grid.Column="1" HorizontalAlignment="Left" Height="628" Margin="10.2,10,0,0" VerticalAlignment="Top" Width="237" Grid.RowSpan="2" ItemsSource="{Binding Parts}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type viewModels:VM_Part}" ItemsSource="{Binding VM_Steps}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding SequenceNumber}" />
<TextBlock Text=" - "></TextBlock>
<TextBlock Text="{Binding PartNumber}" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type viewModels:VM_Step}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
This在我看来是我需要的壁橱示例。我尝试了第一个回答建议
<TreeView.Resources>
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected"
Value="{Binding Path=IsSelected, Mode=TwoWay}" />
</Style>
</TreeView.Resources>
但是,此代码似乎假设IsSelected位于VM_Main而不是VM_Part或VM_Step
答案 0 :(得分:1)
层次结构中的每个TreeViewItem
有自己的DataContext(VM_Part或VM_Step)
因此,如果VM_Part
和VM_Step
具有IsSelected属性,则正确定义TreeViewItem的样式
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected"
Value="{Binding Path=IsSelected, Mode=TwoWay}" />
</Style>
然而,TreeView中的多选可能更简单,CheckBoxes添加到项模板并绑定到视图模型IsSelected属性:
<HierarchicalDataTemplate DataType="{x:Type viewModels:VM_Part}" ItemsSource="{Binding VM_Steps}">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{Binding SequenceNumber}" />
<TextBlock Text=" - "/>
<TextBlock Text="{Binding PartNumber}" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type viewModels:VM_Step}">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>