WPF:如何设置内容控制的数据模板触发器? [英] WPF: How to set the data template trigger for content control?

查看:22
本文介绍了WPF:如何设置内容控制的数据模板触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含一个组合框和一个内容控件的用户控件.在组合框中所做的选择应确定内容控件将使用的数据模板.我已经阅读了这篇文章,它几乎展示了我我正在努力实现.

I want to create a user control that contains one combo box and a content control. The choice made in the combo box should determine the data template the content control would use. I've read this article which pretty much demonstrates what I am trying to achieve.

组合框填充了 enum ModelType 值,可以是 PersonCompany.如果用户选择Person,则内容控件应使用personTemplate数据模板;和 companyTemplate 用于 Company.

The combo box is filled with the enum ModelType values, which can be Person or Company. If the user chooses Person, the content control should use the personTemplate data template; and companyTemplate for Company.

我被内容控件的 XAML 代码困住了.这是我创建的但我无法使其工作的内容:

I got stuck with the XAML code for the content control. Here is what I have created but I can't make it work:

<UserControl.Resources>
  ...
  <DataTemplate x:Key="personTemplate" ...>
  <DataTemplate x:Key="companyTemplate" ...>
  ...
</UserControl.Resources>
...
<ContentControl x:Name="Account">
  <ContentControl.ContentTemplate>
    <DataTemplate>
      <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding AccountType}" Value="Person">
        <!-- I doubt the Value property is set correctly. -->
        <!-- It should be a value of an enum ModelType -->
          <Setter 
              TargetName="Account" 
              Property="ContentTemplate" 
              Value="{StaticResource personTemplate}" />
          <!-- The setter is unaware of the target name, i.e. content control -->
        </DataTrigger>
        <DataTrigger Binding="{Binding AccountType}" Value="Company">
          <Setter 
              TargetName="Account" 
              Property="ContentTemplate" 
              Value="{StaticResource companyTemplate}" />
        </DataTrigger>
      </DataTemplate.Triggers>
    </DataTemplate>
  </ContentControl.ContentTemplate>                    
</ContentControl>

请帮忙,谢谢.

推荐答案

我真的让它工作了.:)

I actually got it to work. :)

XAML 应该是这样的:

Here's what the XAML is supposed to look like:

<ContentControl Content="{Binding}">
  <ContentControl.Style>
    <Style TargetType="ContentControl">
      <Style.Triggers>
        <DataTrigger Binding="{Binding AccountType}" Value="Person">
          <Setter Property="ContentTemplate" Value="{StaticResource personTemplate}" />
        </DataTrigger>
        <DataTrigger Binding="{Binding AccountType}" Value="Company">
          <Setter Property="ContentTemplate" Value="{StaticResource companyTemplate}" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ContentControl.Style>
</ContentControl>

枚举的值也很好用.我希望这可以帮助一些有需要的人.

The values of the enum also work well. I hope this helps some people in need.

这篇关于WPF:如何设置内容控制的数据模板触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆