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

时间:2012-04-17 12:04:15

标签: wpf xaml data-binding datatemplate

我有一个名为

的视图模型
 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集合中的boolean使用不同的datatemplate。做这个的最好方式是什么?

我知道我可以使用不同的ViewModel执行此操作并使用一种基于ViewModel的对象,但我更喜欢使用1种视图模型。

编辑:

我想用数据触发器来做这件事。有人可以提供一些代码吗?

2 个答案:

答案 0 :(得分:68)

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

以下是我在my blog上发布的根据绑定属性交换模板的示例

<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也可以使用,但前提是确定要显示哪个模板的属性不会更改,因为DataTemplateSelectors不响应更改通知。我通常会尽可能地避免使用它们,因为我也更喜欢我的视图选择逻辑,所以我可以看到最新情况。

答案 1 :(得分:-1)

如果你想在ViewModelClass布尔值的情况下切换你的itemscontrol项目视图,那么你可以在ProjectInfoView用户控件中使用数据触发器样式。