如何将WPF xaml表单的Design DataContext设置为使用泛型类型参数的类

Tod*_*Tod 10 wpf datacontext xaml

最初我的.xaml表单使用以下行来设置Designer的DataContext,其中视图模型是非泛型类型(注意我在谈论设计时DataContext而不是将在运行时使用的实际DataContext).

<Window ...
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
d:DataContext="{d:DesignInstance Dialogs:CustomerSearchDlogViewModel}"
...>
Run Code Online (Sandbox Code Playgroud)

现在我没有CustomerSearchDlogViewModel,而是有一个通用的SearchDialogViewModel,但我无法弄清楚<Window>标签中的哪种语法可以让我指定该视图模型.

H.B*_*.B. 18

除非标记扩展(DesignInstance)提供传递类型参数的属性,否则这是不可能的,我怀疑.所以,你可能要继承的建议或写它创建通用的情况下(其实也就是我在做什么你自己的标记扩展现在).

编辑:此扩展应该这样做:

public class GenericObjectFactoryExtension : MarkupExtension
{
    public Type Type { get; set; }
    public Type T { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var genericType = Type.MakeGenericType(T);
        return Activator.CreateInstance(genericType);
    }
}
Run Code Online (Sandbox Code Playgroud)

最初我在从类型名称获取对象类型时遇到了一些问题,但是您可以让XAML解析器为您解析整齐的类型:

DataContext="{me:GenericObjectFactory Type={x:Type Dialogs:CustomerSearchDlogViewModel`1},
                                      T=Data:Customer}"
Run Code Online (Sandbox Code Playgroud)

(注意`1最后引用泛型类型.如果丢弃x:Type包装,反引号将导致错误.)