【发布时间】:2009-12-13 20:11:59
【问题描述】:
我有这个标记扩展
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 也是如此)。正如我所料,控件的数据上下文设置为System.Type for Nullable<int>。
但是,当我使用此扩展程序尝试设置 DataTemplate 的 DataType 属性时
<DataTemplate DataType="{My:Nullable System:Int32}">
<TextBlock ... />
</DataTemplate>
编译器告诉我,
字典的键不能是类型 'System.Windows.Controls.Primitives.TextBlock'。只有字符串, 支持 TypeExtension 和 StaticExtension。"
和
"'NullableExtension' 类型的构造函数没有 1 个参数。
有谁知道为什么只允许使用这三种方法(甚至像我的那样,甚至 TypeExtension 的子类都不允许)?那时处理 XAML 有什么特别之处?还有另一种方法来实现这一点(基于可能为空的类型选择数据模板)而不诉诸DataTemplateSelector?
【问题讨论】:
标签: wpf xaml datatemplate