基于成员变量的不同视图/数据模板 [英] Different views / data template based on member variable
问题描述
我有一个视图模型称为
ViewModelClass
其中包含一个布尔值。
wich contains a boolean.
我有另一个视图模型,其中包含
I have another view model which contains
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集合中的布尔值使用不同的数据表。这样做最好的方法是什么?
Now I want, based on the boolean in the AllProjects-collection, to use a different datatemplate. What is the best way to do this?
我知道我可以使用不同的ViewModel来执行此操作,并使用一种ViewModel基础对象,但我更喜欢使用1视图模型。
I know I can do this with different ViewModels and use a kind of ViewModel-base object, but I prefer just to use 1 view model.
编辑:
我想用数据触发器来做到这一点。有人可以给我一些代码吗?
I want to do this with data triggers. Can someone provide me with some code please?
推荐答案
我通常使用 ContentControl
显示数据,并根据更改的属性在触发器中交换 ContentTemplate
。
I usually use a ContentControl
to display the data, and swap out the ContentTemplate
in a trigger based on the property that changes.
以下是我在我的博客根据绑定属性交换模板
Here's an example I have posted on my blog that swaps a template based on a bound property
<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
不会更改通知。我通常可以避免他们,因为我也喜欢我的观点选择逻辑,所以我可以看到发生了什么。
A DataTemplateSelector
will also work, but only if the property that determines which template to show doesn't change since DataTemplateSelectors
don't respond to change notifications. I usually avoid them if possible since I also prefer my view selection logic in my view so I can see whats going on.
这篇关于基于成员变量的不同视图/数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!