Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to set the data template trigger for content control?

Tags:

wpf

xaml

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.

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.

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> 

Please help, thanks.

like image 443
Boris Avatar asked Apr 24 '11 15:04

Boris


1 Answers

I actually got it to work. :)

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.

like image 158
Boris Avatar answered Oct 19 '22 07:10

Boris