使用DataTrigger将不同的视图应用于同一ViewModel

时间:2014-02-11 17:23:17

标签: wpf mvvm datatemplate datatrigger

我有一个ViewModel,我创建了一个bool DisplaySummary属性。如果是这样,则使用SummaryView来呈现该ViewModel,否则将使用DatailedView

我对如何从这里开始表示怀疑:

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

编辑:起初我尝试使用DataTemplateSelector,但由于它没有响应PropertyChanged,我不得不使用DataTriggers。

1 个答案:

答案 0 :(得分:6)

使用DataTrigger切换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>
相关问题