WPF:如何为内容控件设置数据模板触发器?

42
我想创建一个包含一个组合框和内容控件的用户控件。在组合框中选择的选项应该确定内容控件使用的数据模板。我阅读了 这篇文章,它几乎展示了我要实现的内容。
组合框填充了枚举型 ModelType 的值,可以是 Person 或 Company。如果用户选择 Person,则内容控件应使用 personTemplate 数据模板;对于 Company 则使用 companyTemplate。
我在内容控件的 XAML 代码中卡住了。这里是我创建的内容,但我无法使其工作:
<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>

请帮忙,谢谢。


小提示:模板必须是 DataTemplate 而不是 ControlTemplate。 - Chrigi
1个回答

105

我实际上让它工作了。 :)

这是 XAML 应该看起来的样子:

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

枚举的值也能很好地工作。


11
你们有小费罐吗?我该如何给你买瓶啤酒呢? - gonzobrains
3
请勿将默认值设置为 <ContentControl ContentTemplate="..defaultTemplate.." ...,否则触发器将无法正常工作。您可以通过 Setter 设置默认值:<Setter Property="ContentTemplate" Value="..defaultTemplate.."。 - aderesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接