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

hel*_*ker 3 wpf datatrigger datatemplate mvvm

我有一个ViewModel,我在其中创建了一个bool DisplaySummary属性.如果是这样,SummaryView则使用a来渲染ViewModel,否则DatailedView使用a.

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

Roh*_*ats 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>
Run Code Online (Sandbox Code Playgroud)