wpf - 基于成员变量的不同 View /数据模板

标签 wpf xaml data-binding datatemplate

我有一个名为的 View 模型

 ViewModelClass 
其中包含一个 bool 值。
我有另一个 View 模型,其中包含
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-collection 中的 bool 值使用不同的数据模板。做这个的最好方式是什么?
我知道我可以使用不同的 ViewModel 来做到这一点,并使用一种基于 ViewModel 的对象,但我更喜欢只使用一个 View 模型。
编辑:
我想用数据触发器来做到这一点。有人可以给我一些代码吗?

最佳答案

我通常使用 ContentControl显示数据,并换出 ContentTemplate在基于更改的属性的触发器中。

这是我在 my blog 上发布的示例基于绑定(bind)属性交换模板

<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 以来没有改变。不响应更改通知。如果可能,我通常会避免使用它们,因为我也更喜欢 View 中的 View 选择逻辑,这样我就可以看到发生了什么。

关于wpf - 基于成员变量的不同 View /数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10190887/

相关文章:

wpf - 为什么 XAML 的 Margin 属性有四个组件而不是两个?

.net - 使用 WPF 双向数据绑定(bind)时更改 setter 属性中的值

wpf - XAML 中带有撇号的 StringFormat 绑定(bind)不起作用

c# - WPF - 组合框 SelectionChanged => 更改文本框绑定(bind)

c# - 在 Wpf 中获取祖先源

c# - 在csproj文件中配置XamlRuntime和DefaultXamlRuntime意义

c# - 加载外部字体并在 C# 中使用它

WPF RibbonApplicationMenuItem 命令绑定(bind)

c# - WPF 动画未触发

c# - 文本 block 文本选择