I have this markup extension
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 );
}
}
which is designed to provide a nullable version of some other type. It works as expected when used in "normal" XAML. For example, as in
<SomeControl DataContext="{My:Nullable System:Int32}"/>
(assuming that My is the XML namespace defined for the C# namespace holding the extension, and similarly for System). The data context for the control gets set to a System.Type
for Nullable<int>
as I expect.
However, when I use this extension to try and set the DataType
property of a DataTemplate
like
<DataTemplate DataType="{My:Nullable System:Int32}">
<TextBlock ... />
</DataTemplate>
I am told, by the compiler, that "A key for a dictionary cannot be of type 'System.Windows.Controls.Primitives.TextBlock'. Only String, TypeExtension, and StaticExtension are supported." and "No constructor for type 'NullableExtension' has 1 parameters."
Does anybody know why only those three methods (and not even subclasses of TypeExtension
, like mine is) are allowed? What is special about the processing of the XAML at that point? And is there another way to accomplish this (data template selection based on types that may be nullable) without resorting to a DataTemplateSelector
?