基于成员变量的不同视图/数据模板

27

我有一个名为

view model

的视图模型。

 ViewModelClass 

其中包含一个布尔值。

我有另一个包含的视图模型

ObservableCollection<ViewModelClass> m_allProjects;

然后我在我的视图中有这个:

<DataTemplate>
   <views:ProjectInfoView x:Key="ProjectInfoDetailTemplate"/>
</DataTemplate>

<ItemsControl Grid.Row="1" Grid.Column="0"
              ItemsSource="{Binding AllProjects}"
              ItemTemplate="{StaticResource ProjectInfoDetailTemplate}"
              Margin="10,28.977,10,10">
</ItemsControl >

基于AllProjects集合中的布尔值,我想使用不同的数据模板。最好的方法是什么?

我知道可以使用不同的ViewModel并使用一种ViewModel基对象,但我更喜欢只使用1个ViewModel。

编辑:

我希望使用数据触发器来实现这一点。 请有人提供给我一些代码吗?

1个回答

83

我通常使用ContentControl来显示数据,并在触发器中根据更改的属性交换ContentTemplate

以下是我在我的博客上发布的示例,它基于绑定的属性切换模板。

<DataTemplate x:Key="PersonTemplate" DataType="{x:Type local:ConsumerViewModel}">
     <TextBlock Text="I'm a Person" />
</DataTemplate> 

<DataTemplate x:Key="BusinessTemplate" DataType="{x:Type local:ConsumerViewModel}">
     <TextBlock Text="I'm a Business" />
 </DataTemplate>

<DataTemplate DataType="{x:Type local:ConsumerViewModel}">
     <ContentControl Content="{Binding }">
         <ContentControl.Style>
             <Style TargetType="{x:Type ContentControl}">
                 <Setter Property="ContentTemplate" Value="{StaticResource PersonTemplate}" />
                 <Style.Triggers>
                     <DataTrigger Binding="{Binding ConsumerType}" Value="Business">
                         <Setter Property="ContentTemplate" Value="{StaticResource BusinessTemplate}" />
                     </DataTrigger>
                 </Style.Triggers>
             </Style>
         </ContentControl.Style>
     </ContentControl>
 </DataTemplate>

DataTemplateSelector也可以起作用,但前提是决定显示哪个模板的属性不会发生变化,因为DataTemplateSelector不能响应更改通知。如果可能的话,我通常会避免使用它们,因为我也更喜欢将视图选择逻辑放在视图中,这样我就可以看到发生了什么。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接