Change Data template dynamically

后端 未结 2 674
自闭症患者
自闭症患者 2020-11-29 23:20

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.

<
相关标签:
2条回答
  • 2020-11-29 23:55

    Just a quick note for anyone that found this incredibly helpful as I did -

    Currently with WPF, it looks like you'll want to use DataType rather than TargetType on your DataTemplate definitions:

    <DataTemplate x:Key="OpenTaskTemplate" DataType="{x:Type local:TaskModel}">
         <TextBlock Text="I'm an Open Task" />
    </DataTemplate> 
    
    <DataTemplate x:Key="ClosedTaskTemplate" DataType="{x:Type local:TaskModel}">
         <TextBlock Text="I'm a Closed Task" />
     </DataTemplate>
    
    0 讨论(0)
  • 2020-11-30 00:13

    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>
    
    0 讨论(0)
提交回复
热议问题