动态更改数据模板 [英] Change Data template dynamically
问题描述
我有一个绑定到任务的项目控件。每个任务都有任务状态。我为每个任务状态定义了不同的数据模板,以及数据模板选择器。
I have a item control which is bound to Tasks. Each task has task state. I have defined different data templates for each task state, and also data template selector.
问题是我无法弄清楚在任务执行时如何触发数据模板选择器状态会动态更改。
Problem is that I am not able to figure out how to trigger data template selector when task state is changed dynamically.
我想知道如何将数据触发器与数据模板一起使用。
如果无法解决,我将探索其他替代方法,例如
1.绑定到任务状态的附加属性。任何更改都会动态设置数据模板。
2. Visual State Manager
If this will not work out, i will explore other alternatives such as
1. Attached Property bound to task state. Any change will dynamically set data template.
2. Visual State Manager
推荐答案
A DataTemplateSelector
不响应 PropertyChange
通知,因此当属性更改时不会重新评估。
A DataTemplateSelector
does not respond to PropertyChange
notifications, so it doesn't get re-evaluated when your properties change.
我使用的替代方法是 DataTriggers
,它根据属性更改模板
。
The alternative I use is DataTriggers
that changes the Template
based on a property.
例如,这将使用 ContentControl $ c绘制所有
TaskModel
对象$ c>,而 ContentControl.Template
基于 TaskModel的
TaskStatus
属性
For example, this will draw all TaskModel
objects using a ContentControl
, and the ContentControl.Template
is based on the TaskStatus
property of the TaskModel
<DataTemplate x:Key="OpenTaskTemplate" TargetType="{x:Type local:TaskModel}">
<TextBlock Text="I'm an Open Task" />
</DataTemplate>
<DataTemplate x:Key="ClosedTaskTemplate" TargetType="{x:Type local:TaskModel}">
<TextBlock Text="I'm a Closed Task" />
</DataTemplate>
<DataTemplate DataType="{x:Type local:TaskModel}">
<ContentControl Content="{Binding }">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<!-- Default Template -->
<Setter Property="ContentTemplate" Value="{StaticResource OpenTaskTemplate}" />
<!-- Triggers to change Template -->
<Style.Triggers>
<DataTrigger Binding="{Binding TaskStatus}" Value="Closed">
<Setter Property="ContentTemplate" Value="{StaticResource ClosedTaskTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
这篇关于动态更改数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!