43

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.

1
  • Little sidenote: The template has to be a DataTemplate not a ControlTemplate Commented Aug 1, 2021 at 20:06

1 Answer 1

106

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you have a tip jar somewhere? How can I send you a beer?
be sure not to put a default value as <ContentControl ContentTemplate="..defaultTemplate.." ... - triggers won't work. You can set default value in a setter: <Setter Property="ContentTemplate" Value="..defaultTemplate.."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.