[英]Tree View IsSelected with hierarchical data template
我發現了在視圖模型中綁定IsSelected屬性的幾個示例。 但是,這些都沒有處理帶有Hierachical數據模板的TreeView。
我的希拉基就像這樣
我希望能夠在一個部分下選擇多個VM_Part實例或多個VM_Step。 我的想法是可以擁有一個上下文菜單,並在所選項目上執行各種命令
<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>
在我看來, 這似乎是我所需要的壁櫥例子。 我嘗試了第一個回答的建議
<TreeView.Resources>
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected"
Value="{Binding Path=IsSelected, Mode=TwoWay}" />
</Style>
</TreeView.Resources>
但是,似乎此代碼假定IsSelected在VM_Main中,而不在VM_Part或VM_Step中
層次結構中的每個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>
但是,通過將CheckBox添加到項目模板並綁定到視圖模型IsSelected屬性,TreeView中的多選可能更簡單:
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.