【问题标题】:WPF, Xaml and Controls Factory?WPF、Xaml 和控件工厂?
【发布时间】:2010-09-25 22:38:02
【问题描述】:

我想创建由几个其他控件组成的 WPF 控件。主要问题是如何实现根据Model的类型选择正确的控件?

<MyControl>
<!-- if DataContext.GetType() == Type1 -->
<Control1 DataContext = {Binding}/>
<!-- if DataContext.GetType() == Type2 -->
<Control2 DataContext = {Binding}>

</MyControl>

我怎样才能很好地实现和设计它?我的想法是放一些类似...

Control CreateControl(object dataContext) {
 if (dataContext.GetType() == TYpe1)
     return new Control1() {DataContext = dataContext}
 if (dataContext.GetType() == TYpe2)
     return new Control2() {DataContext = dataContext}    
}

但我不知道如何调用这样的方法,它在 XAML 中返回 Control...

【问题讨论】:

    标签: wpf design-patterns xaml


    【解决方案1】:

    您可以在资源中定义DataTemplates,并使用ContentControl 作为占位符

    资源:

    <DataTemplate DataType="{x:Type model:Model1}">
        <Control1 />
    </DataTemplate>
    
    <DataTemplate DataType="{x:Type model:Model2}">
        <Control2 />
    </DataTemplate>
    

    (注意不需要显式设置DataContext)

    用法:

    <MyControl>
        <ContentControl Content="{Binding}" />
    </MyControl>
    

    它会根据Content的类型选择合适的DataTemplate

    【讨论】:

      【解决方案2】:

      对于这种情况,您可以使用DataTemplateSelector。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-04
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多