【问题标题】:Where to create UserControl for ContentControl在哪里为 ContentControl 创建 UserControl
【发布时间】:2014-02-02 18:25:43
【问题描述】:

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

所有按钮都绑定到 ViewModel 中的一个命令。应该显示哪个用户控件的决定由带有枚举的命令参数完成,例如:

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

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

我有几个想法:

  1. 将内容直接绑定到 ViewModel 并分配新的 那里有用户控件
  2. 绑定 Enum 并使用转换器创建控件

【问题讨论】:

  • 您是否有针对不同内容的单独用户控件?
  • 是的。对于每个按钮,我都有一个服务器 UserControl

标签: c# wpf mvvm


【解决方案1】:

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

  1. 为您拥有的多个用户控件创建DataTemplates,并将它们放在窗口资源下。
  2. 在您的窗口中有一个ContentControl,并将其内容绑定到 ViewModel 中的选定内容属性。
  3. 创建一个ContentTemplateSelector 并根据选择的内容返回相应的DataTemplate。

XAML:

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

参考示例here

这样以后如果你需要添加其他内容,你所要做的就是在资源下为它创建一个DataTemplate,然后在ContentSelector中打勾就可以了。 (易于扩展)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 2012-08-24
    • 2014-10-04
    • 2015-12-09
    • 2016-03-15
    • 2015-11-09
    相关资源
    最近更新 更多