Dab*_*rnl 7 .net wpf xaml hierarchicaldatatemplate
我有一个类,MyClass<MyObject>并希望将其设置为HierarchicalDataTemplate的DataType.
XAML中的语法是什么?(我知道如何设置命名空间,我只需要语法
<HierarchicalDataTemplate DataType="{X:Type .....
Run Code Online (Sandbox Code Playgroud)
Szy*_*zga 16
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在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>
Run Code Online (Sandbox Code Playgroud)
这里有一些关键的想法:
WPF 3.x 中不支持此功能(我认为 4.0 中可能会支持,但我不确定);但使用标记扩展很容易设置。
首先,您需要创建一个标记扩展类,它将类型参数作为构造函数参数:
public class MyClassOf : MarkupExtension
{
private readonly Type _of;
public MyClassOf(Type of)
{
_of = of;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return typeof(MyClass<>).MakeGenericType(_of);
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用此标记扩展来代替 x:Type 扩展:
<HierarchicalDataTemplate DataType="{local:MyClassOf {x:Type MyObject}}" />
Run Code Online (Sandbox Code Playgroud)
不用说,这可以推广到允许任意泛型类型的实例化;我没有展示这一点,因为它增加了一点点复杂性。
| 归档时间: |
|
| 查看次数: |
6124 次 |
| 最近记录: |