我尝试使用 MVVM 模式制作一个 View ,该 View 将在一侧显示 TreeView (主视图),对于所选节点,左侧显示一些信息(详细信息)。
TreeView 绑定(bind)在一个 ViewModel 的集合上,实际上是一个抽象类。我有两个继承自抽象 ViewModel 的类,一个代表类别,另一个代表需求。
在树中,类别可能有类别或需求的子项。
要求不能有 child ,他们只是叶子。
即:
- 类别 1
- 要求 1
- 子类别 1
- 第 2 类
- 子类别 2
- 类别 3
我设法在详细 View 中显示抽象类中的一些数据。我的问题是,如果选择了类别或要求,我必须显示不同的数据……我不知道该怎么做。
是否有一个控件可以让我根据树中所选节点的类型显示数据?
我的 XAML 现在看起来像这样:
<Grid DataContext="{Binding Requirements}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="350" />
<ColumnDefinition Width="400*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TreeView
x:Name="treeRequirements"
Grid.Column="0" Grid.Row="0"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
ItemsSource="{Binding}">
<TreeView.ItemContainerStyle>
<!-- This Style binds a TreeViewItem to a PersonViewModel. -->
<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 Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<Grid
Grid.Column="1" Grid.Row="0"
DataContext="{Binding ElementName=treeRequirements, Path=SelectedItem}">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<!-- Name comes from the abstract class, so no problem -->
<TextBlock
Grid.Row="0" Grid.Column="0">
Name
</TextBlock>
<TextBox
Grid.Row="0" Grid.Column="1"
Text="{Binding Path=Name, Mode=TwoWay}" />
</Grid>
</Grid>
我的问题是,我不知道如何根据所选节点表示的 View 模型类型显示不同的细节。我只能显示抽象类的属性。
有什么帮助吗?
编辑
总结一下我的问题,整个 master-detail 和 treeview 与问题无关,只是放在上下文中。我的问题实际上只是根据我的 View 模型的子类型显示不同的字段,这可能会有所不同。
最佳答案
您需要将多个 HierarchicalDataTemplate
声明为资源,并为每个资源指定 DataType
属性。如果您未指定 Treeview.ItemTemplate
,.net 将在运行时选择最匹配的模板并相应地显示数据。
例子:
<TreeView ItemsSource={Binding}>
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Type1}">
...
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Type2}">
...
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
您可能还想阅读以下文章(特别是使用 HierarchicalDataTemplate
的足球示例:http://msdn.microsoft.com/en-us/library/ms742521.aspx
关于c# - 使用具有不同类型详细信息的主从 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5276431/