WPF:如何设置内容控制的数据模板触发器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5771362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF: How to set the data template trigger for content control?
提问by Boris
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 articlewhich pretty much demonstrates what I am trying to achieve.
我想创建一个包含一个组合框和一个内容控件的用户控件。在组合框中所做的选择应确定内容控件将使用的数据模板。我已经阅读了这篇文章,它几乎展示了我想要实现的目标。
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
.
组合框填充了enum ModelType
值,可以是Person
或Company
。如果用户选择Person
,则内容控件应使用personTemplate
数据模板;并companyTemplate
为Company
。
I got stuck with the XAML code for the content control. Here is what I have created but I can't make it work:
我被内容控件的 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>
Please help, thanks.
请帮忙,谢谢。
回答by Boris
I actually got it to work. :)
我真的让它工作了。:)
Here's what the XAML is supposed to look like:
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>
The values of the enum also work well. I hope this helps some people in need.
枚举的值也很好用。我希望这可以帮助一些有需要的人。