public class NullableExtension : TypeExtension
{
public NullableExtension() {
}
public NullableExtension( string type )
: base(type) {
}
public NullableExtension( Type type )
: base(type) {
}
public override object ProvideValue( IServiceProvider serviceProvider ) {
Type basis = (Type)base.ProvideValue( serviceProvider );
return typeof(Nullable<>).MakeGenericType( basis );
}
}
这个类型被设计为提供其他类型的可空版本。在“普通”的XAML中使用时,它的表现符合预期。例如:
<SomeControl DataContext="{My:Nullable System:Int32}"/>
假设 My 是包含扩展的 C# 命名空间定义的 XML 命名空间,System 同理。控件的数据上下文被设置为 Nullable<int>
的 System.Type
,这是我预期的。
然而,当我使用这个扩展来尝试设置 DataTemplate
的 DataType
属性时,出现了问题。
<DataTemplate DataType="{My:Nullable System:Int32}">
<TextBlock ... />
</DataTemplate>
我被编译器告知:
还有一个字典的键不能是'System.Windows.Controls.Primitives.TextBlock'类型。仅支持String、TypeExtension和StaticExtension。
有人知道为什么只允许这三种方法(甚至不包括TypeExtension的子类,比如我的)吗?在那一点上,XAML 的处理有什么特殊之处?还有没有其他方法可以完成这个任务(基于可空类型进行数据模板选择),而不需要使用DataTemplateSelector?没有类型为'NullableExtension'的构造函数有1个参数。
DataType="{x:Type TypeName=System:Nullable\
1[[System.Int32]]}"` 应该可以工作,但在2013年8月,在.NET 4.0下,它并不能正常工作。我发现唯一的解决方法是使用某种MarkupExtension。 - Dan