如何将WPF xaml表单的Design DataContext设置为使用通用类型参数的类 [英] How do I set WPF xaml form's Design DataContext to class that uses generic type parameters

查看:352
本文介绍了如何将WPF xaml表单的Design DataContext设置为使用通用类型参数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Originally my .xaml form used the following line to set the Designer's DataContext where the view model was a non-generic type (note I'm talking about the Design time DataContext not the actual DataContext that will be used at runtime).

<Window ...
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    
d:DataContext="{d:DesignInstance Dialogs:CustomerSearchDlogViewModel}"
...>

现在代替CustomerSearchDlogViewModel我有一个通用的SearchDialogViewModel,但是我不知道哪种语法可以用< Window>标签,让我指定该视图模型。

Now instead of CustomerSearchDlogViewModel I have a generic SearchDialogViewModel but I can't figure out what syntax will work in the <Window> tag to let me specify that view model.

推荐答案

除非标记扩展( DesignInstance )提供,否则不可能属性传递类型参数,我对此表示怀疑。因此,您可能希望按照建议的方式进行子类化或编写自己的标记扩展来创建通用实例(实际上,这就是我现在正在 进行的操作)。

That is not possible unless the markup extension (DesignInstance) provides properties to pass type arguments, which i doubt. So you might want to subclass as suggested or write your own markup extension which creates generic instances (in fact that is what i am doing right now).

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

This extension should do it:

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);
    }
}

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

Initially i had some problems getting the object type from a type-name but you can let the XAML parser resolve the type for you which is neat:

DataContext="{me:GenericObjectFactory Type={x:Type Dialogs:CustomerSearchDlogViewModel`1},
                                      T=Data:Customer}"

(请注意最后的`1 引用泛型类型。如果删除 x:Type 包装反引号会导致错误。)

(Note the `1 at the end to reference a generic type. If you drop the x:Type wrapping the backtick will cause an error.)

这篇关于如何将WPF xaml表单的Design DataContext设置为使用通用类型参数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆