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

查看:35
本文介绍了如何将 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}"
...>

现在我有一个通用的 SearchDialogViewModel 而不是 CustomerSearchDlogViewModel,但我不知道什么语法将在 <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).

这个扩展应该这样做:

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

最初我从类型名称获取对象类型时遇到了一些问题,但您可以让 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天全站免登陆