0
votes

In my application I have a window with several buttons on the top. By a click on one button a usercontrol is displayed in a contentcontrol under the buttons.

All buttons are bound to one Command in the ViewModel. The decission which usercontrol should be displayed is done by the commandparameter with an enum like:

<Button Content="Pupils" Margin="3" Height="30" Command="{Binding OpenSectionCommand}" CommandParameter="{x:Static local:SectionType.Section1}"/>

My question now is: Where shall I create the new Usercontrol and assign it to the ContentControl?

I had several ideas:

  1. Bind the Content direct to the ViewModel and assign the new UserControl there
  2. Bind the Enum and use a converter to create the control
1
Do you have separate UserControls for different Content?Rohit Vats
Yes. For each button I have a serveral UserControlTomtom

1 Answers

1
votes

Since for each type of Content you have separate UserControls, i would suggest to use ContentTemplateSelector.

  1. Create DataTemplates for multiple userControls you have and put them under window resources.
  2. Have a ContentControl in your window and bind its Content to selected content property in ViewModel.
  3. Create a ContentTemplateSelector and based on content selected return corresponding DataTemplate.

XAML:

<ContentControl Content="{Binding SelectedContent}"
                ContentTemplateSelector="{StaticResource ContentSelector}"/>

Refer to the example here.

This way in future if you need to add another content, all you had to do is create a DataTemplate for it under resources and put the check in ContentSelector and you are good to go. (easily extensible).