【发布时间】:2010-08-05 14:30:18
【问题描述】:
此问题与“How to reference a generic type in the DataType attribute of a HierarchicalDataTemplate?”的答案密切相关
我遵循该答案的基本思想并创建了这个数据结构:
<!-- for DictItemVM<string, Remote.Address> which is a viewmodel for a KeyValuePair<...> -->
<x:Array Type="{x:Type sys:Type}"
x:Key="KVParamsStringToRemoteAddress"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:remote="clr-namespace:Remote"
xmlns:mvvm="clr-namespace:MVVM">
<x:Type TypeName="sys:String" />
<mvvm:GenericType BaseType="{x:Type TypeName=remote:Address}"/>
</x:Array>
<mvvm:GenericType xmlns:mvvm="clr-namespace:MVVM"
BaseType="{x:Type TypeName=mvvm:DictItemVM`2}"
InnerTypes="{StaticResource KVParamsStringToRemoteAddress}"
x:Key="DictItemVMOfStringToRemoteAddress"/>
DictItemVM<T,U> 是 KeyValuePair<...> 的视图模型,源自 BaseVM。 BaseVM 有一个 DataTemplate 视图,但我正在努力为DictItemVM<string, Remote.Address> 创建一个视图。
Remote.Address 是一个复杂的值类型(存储路径和访问信息)。 Remote.Address 有自己的 DataTemplate 视图。
所以现在我有了 StaticResource “DictItemVMOfStringToRemoteAddress”,我想用它来指定一个 DataTemplate:
<DataTemplate x:Key="TestKey" DataType="{StaticResource DictItemVMOfStringToRemoteAddress}">
<StackPanel>
<Label Content="UniqueName" />
<TextBox Text="{Binding UniqueName}" />
<Label Content="Key"/>
<TextBox Text="{Binding Key, Mode=OneWay}" IsEnabled="False" />
<Label Content="Value"/>
<ContentControl Content="{Binding Value, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
现在这个 DataTemplate应该被用作视图,而是显示 BaseVM 的视图。
有人给我这个提示吗?
[编辑:2010-08-09]
我尝试了一些事情:
在我替换的 x:Array 定义中<mvvm:GenericType BaseType="{x:Type TypeName=remote:Address}"/>
与<x:Type TypeName="remote:Address"/>,
因为它基本上就是这样 - 没有区别。
还尝试在标签之间创建 DataType(而不是链接到静态资源),如下所示:
<DataTemplate x:Key="TestKey">
<DataTemplate.DataType>
<Binding>
<Binding.Source>
<mvvm:GenericType
BaseType="{x:Type TypeName=mvvm:DictItemVM`2}">
<mvvm:GenericType.InnerTypes>
<x:Type TypeName="sys:String" />
<x:Type TypeName="remote:Address"/>
</mvvm:GenericType.InnerTypes>
</mvvm:GenericType>
</Binding.Source>
</Binding>
</DataTemplate.DataType>
在 GenericType.InnerTypes 中使用和不使用 x:Array 进行了尝试,都给了我this 错误。
尝试从静态属性传递类型,如下所示:DataType="{x:Static mvvm:StaticTypes.DictItemVMOfStringToRemoteAddress}"
像这样:DataType="{Binding Path={x:Static mvvm:StaticTypes.DictItemVMOfStringToRemoteAddress}}"
没有区别。
奇怪的是,这个特定的 DataTemplate 需要有一些 x:Key 值,而 xaml 资源文件中的所有其他值都指向常规类型,例如:DataType="{x:Type mvvm:EffectVM}"。如果我删除 x:Key,我会收到 this 错误。
【问题讨论】:
标签: .net wpf generics xaml markup-extensions