Search code examples
wpfmvvmdatatemplatedatatrigger

Using DataTrigger to apply different Views to the same ViewModel


I have a ViewModel where I created a bool DisplaySummary property. When this is true, a SummaryView is to be use to render that ViewModel, otherwise a DatailedView is to be used.

I am in doubt about how I should proceed from here:

<DataTemplate DataType="{x:Type vm:AwesomeViewModel}">
    <ContentControl Content="{Binding}">
        <ContentControl.Style>
            <Style>
                 #### WHAT I SHOULD PUT HERE?
            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>

<DataTemplate x:Key="SummaryTemplate">
    <vw:SummaryViewScreen />
</DataTemplate>

<DataTemplate x:Key="DetailedTemplate">
    <vw:DetailedViewScreen />
</DataTemplate>

EDIT: at first I tried to use DataTemplateSelector, but since it does not respond to PropertyChanged, I had to use DataTriggers.


Solution

  • Use DataTrigger to switch ContentTemplate:

    <DataTemplate DataType="{x:Type vm:AwesomeViewModel}">
      <ContentControl Content="{Binding}">
        <ContentControl.Style>
          <Style TargetType="ContentControl">
            <Setter Property="ContentTemplate"
                    Value="{StaticResource DetailedTemplate}"/>
               <Style.Triggers>
                 <DataTrigger Binding="{Binding DisplaySummary}" Value="True">
                    <Setter Property="ContentTemplate"
                            Value="{StaticResource SummaryTemplate}"/>
                  </DataTrigger>
                </Style.Triggers>
           </Style>
         </ContentControl.Style>
       </ContentControl>
     </DataTemplate>