【问题标题】:Using DataTrigger to apply different Views to the same ViewModel使用 DataTrigger 将不同的 View 应用到同一个 ViewModel
【发布时间】:2014-02-11 17:23:17
【问题描述】:

我有一个 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。

【问题讨论】:

    标签: wpf mvvm datatemplate datatrigger


    【解决方案1】:

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

    【讨论】:

    • 啊哈!我认为ContentTemplate 是缺失的链接。马上尝试并尽快提供反馈!
    • 好吧,我在这里遇到了绑定问题。显然使用&lt;ContentControl Content={Binding}&gt; 是不够的。此处 (stackoverflow.com/a/18868668/401828) 和此处 (stackoverflow.com/a/15389304/401828) 在各自的短语中提供了一些相关信息“当您在 CellTemplate 内执行绑定时,您实际上是绑定到单元格的 DataContext 而不是视图的 DataContext(即视图模型) 。”和“仅设置 ContentTemplate 属性是不够的。ContentControl 不会隐式使用其 DataContext 作为内容。”
    • 使用您的代码,我得到“无法将 Ms.Internal.NamedObject 转换为 System.Windows.DataTemplate”,如果我完全删除 ContentControl.Style,只需保留 Content="{Binding}",这种情况就会继续发生部分(然后它得到一个无限递归)...... :(
    • unable to cast Ms.Internal.NamedObject to System.Windows.DataTemplate - 确保拼写资源名称与资源声明中的内容完全相同,因为资源查找区分大小写。还要确保资源DetailedTemplateSummaryTemplatevm:AwesomeViewModel 的DataTemplate 之前在XAML 中定义。
    • 哇,它工作了!这是您的第二个提示:我指的是在 XAML 中声明它之前的 StaticResource。只需反转源文件中的顺序就可以了。使用 WPF/XAML 可以轻松地拔掉很多头发,真是令人惊讶……
    猜你喜欢
    • 2014-06-19
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多