我有一个MyClass<MyObject>类,想将其设置为HierarchicalDataTemplate的DataType。XAML中的语法是什么? (我知道如何设置 namespace ,我只需要语法<HierarchicalDataTemplate DataType="{X:Type ..... 最佳答案 itowlson的方法不错,但这只是一个开始。以下是适用于您的案例(以及大多数(如果不是全部)案例)的内容:public class GenericType : MarkupExtension{ public Type BaseType { get; set; } public Type[] InnerTypes { get; set; } public GenericType() { } public GenericType(Type baseType, params Type[] innerTypes) { BaseType = baseType; InnerTypes = innerTypes; } public override object ProvideValue(IServiceProvider serviceProvider) { Type result = BaseType.MakeGenericType(InnerTypes); return result; }}然后,您可以在XAML中创建具有任何深度级别的任何类型。例如: <Grid.Resources> <x:Array Type="{x:Type sys:Type}" x:Key="TypeParams"> <x:Type TypeName="sys:Int32" /> </x:Array> <local:GenericType BaseType="{x:Type TypeName=coll:List`1}" InnerTypes="{StaticResource TypeParams}" x:Key="ListOfInts" /> <x:Array Type="{x:Type sys:Type}" x:Key="DictionaryParams"> <x:Type TypeName="sys:Int32" /> <local:GenericType BaseType="{x:Type TypeName=coll:List`1}" InnerTypes="{StaticResource TypeParams}" /> </x:Array> <local:GenericType BaseType="{x:Type TypeName=coll:Dictionary`2}" InnerTypes="{StaticResource DictionaryParams}" x:Key="DictionaryOfIntsToListOfInts" /> </Grid.Resources>这里有一些关键思想:必须使用标准`表示法指定通用类型。因此, System.Collections.Generic.List 是 System.Collections.Generic.List`1 。字符`表示类型是通用的,其后的数字表示类型具有的通用参数的数量。 x:Type标记扩展可以很容易地检索这些基本的泛型类型。 通用参数类型作为Type对象的数组传递。然后将此数组传递到MakeGenericType(...)调用中。
10-05 18:36