在哪里为ContentControl创建UserControl

时间:2014-02-02 18:25:43

标签: c# wpf mvvm

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

所有按钮都绑定到ViewModel中的一个命令。应该显示usercontrol的decission由命令参数完成,枚举如:

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

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

我有几个想法:

  1. 将内容直接绑定到ViewModel并分配新内容 UserControl那里
  2. 绑定枚举并使用转换器创建控件

1 个答案:

答案 0 :(得分:1)

由于每种Content类型都有UserControls,我建议使用ContentTemplateSelector

  1. 为您拥有的多个userControl创建DataTemplates并将它们放在窗口资源下。
  2. 在您的窗口中设置ContentControl并将其内容绑定到ViewModel中的选定内容属性。
  3. 创建ContentTemplateSelector并根据所选内容返回相应的DataTemplate。
  4. XAML:

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

    请参阅示例here

    将来如果您需要添加其他内容,您只需在资源下为其创建DataTemplate,然后将检查放入ContentSelector,您就可以了。 (易于扩展)。

相关问题