Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

wpf - 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.

I want to know how to use data triggers together with data templates.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A DataTemplateSelector does not respond to PropertyChange notifications, so it doesn't get re-evaluated when your properties change.

The alternative I use is DataTriggers that changes the Template based on a property.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...