简体   繁体   English

在哪里为ContentControl创建UserControl

[英]Where to create UserControl for ContentControl

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. 所有按钮都绑定到ViewModel中的一个Command。 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? 现在我的问题是:我应该在哪里创建新的Usercontrol并将其分配给ContentControl?

I had several ideas: 我有几个想法:

  1. Bind the Content direct to the ViewModel and assign the new UserControl there 将内容直接绑定到ViewModel并在那里分配新的UserControl
  2. Bind the Enum and use a converter to create the control 绑定枚举并使用转换器创建控件

Since for each type of Content you have separate UserControls , i would suggest to use ContentTemplateSelector . 由于每种Content类型都有单独的UserControls ,因此建议您使用ContentTemplateSelector

  1. Create DataTemplates for multiple userControls you have and put them under window resources. 为您拥有的多个userControl创建DataTemplates并将其放在窗口资源下。
  2. Have a ContentControl in your window and bind its Content to selected content property in ViewModel. 在窗口中具有ContentControl ,并将其Content绑定到ViewModel中的选定内容属性。
  3. Create a ContentTemplateSelector and based on content selected return corresponding DataTemplate. 创建一个ContentTemplateSelector并根据选择的内容返回相应的DataTemplate。

XAML: 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. 将来,如果您需要添加其他内容,则只需在资源下为其创建一个DataTemplate并将检查内容放入ContentSelector ,就可以了。 (easily extensible). (易于扩展)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM