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

Jos*_*and 18 data-binding wpf xaml datatemplate

我有一个名为的视图模型

 ViewModelClass 
Run Code Online (Sandbox Code Playgroud)

它包含一个布尔值.

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

ObservableCollection<ViewModelClass> m_allProjects;
Run Code Online (Sandbox Code Playgroud)

然后我在我看来有这个:

<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 >
Run Code Online (Sandbox Code Playgroud)

现在我希望,基于AllProjects集合中的布尔值,使用不同的datatemplate.做这个的最好方式是什么?

我知道我可以用不同的ViewModel做这个并使用一种基于ViewModel的对象,但我更喜欢使用1个视图模型.

编辑:

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

Rac*_*hel 71

我通常使用a 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>
Run Code Online (Sandbox Code Playgroud)

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