最初,我的 .xaml 表单使用以下行来设置设计器的 DataContext,其中 View 模型是非通用类型(注意我说的是设计时 DataContext,而不是将在以下位置使用的实际 DataContext)运行时)。
<Window ...
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d:DataContext="{d:DesignInstance Dialogs:CustomerSearchDlogViewModel}"
...>
现在我有一个通用的 SearchDialogViewModel 而不是 CustomerSearchDlogViewModel,但我无法弄清楚在
最佳答案
这是不可能的,除非标记扩展(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);
}
}
最初,我在从类型名称获取对象类型时遇到了一些问题,但您可以让 XAML 解析器为您解析类型,这很简洁:
DataContext="{me:GenericObjectFactory Type={x:Type Dialogs:CustomerSearchDlogViewModel`1},
T=Data:Customer}"
(请注意末尾的 `1
来引用泛型类型。如果删除包裹反引号的 x:Type
将导致错误。)
关于wpf - 如何将 WPF xaml 表单的 Design DataContext 设置为使用泛型类型参数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8235421/