C# 在何处为ContentControl创建UserControl

C# 在何处为ContentControl创建UserControl,c#,wpf,mvvm,C#,Wpf,Mvvm,在我的应用程序中,我有一个顶部有几个按钮的窗口。通过单击一个按钮,用户控件将显示在按钮下的contentcontrol中 所有按钮都绑定到ViewModel中的一个命令。应显示哪个usercontrol的决定由commandparameter通过枚举完成,例如: <Button Content="Pupils" Margin="3" Height="30" Command="{Binding OpenSectionCommand}" CommandParameter="{x:Static

在我的应用程序中,我有一个顶部有几个按钮的窗口。通过单击一个按钮,用户控件将显示在按钮下的contentcontrol中

所有按钮都绑定到ViewModel中的一个命令。应显示哪个usercontrol的决定由commandparameter通过枚举完成,例如:

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

我现在的问题是:我应该在哪里创建新的Usercontrol并将其分配给ContentControl

我有几个想法:

  • 将内容直接绑定到ViewModel并指定新的 用户控制
  • 绑定枚举并使用转换器创建控件

  • 因为对于每种类型的
    内容
    都有单独的
    用户控件
    ,我建议使用

  • 为您拥有的多个用户控件创建
    DataTemplates
    ,并将它们放在窗口资源下
  • 在窗口中设置
    ContentControl
    ,并将其内容绑定到ViewModel中的选定内容属性
  • 创建一个
    ContentTemplateSelector
    ,并根据所选内容返回相应的数据模板
  • XAML:

    
    
    请参考示例


    这样,将来如果您需要添加其他内容,只需在参考资料下为其创建一个
    DataTemplate
    ,并将签入
    ContentSelector
    ,就可以了。(易于扩展)。

    您是否有针对不同内容的单独用户控件?是的。对于每个按钮,我都有一个服务器用户控件
    <ContentControl Content="{Binding SelectedContent}"
                    ContentTemplateSelector="{StaticResource ContentSelector}"/>