Skip to content

Instantly share code, notes, and snippets.

@cerebrate
Created September 25, 2013 04:12
Show Gist options
  • Save cerebrate/6695095 to your computer and use it in GitHub Desktop.
Save cerebrate/6695095 to your computer and use it in GitHub Desktop.
The markup extension that's supposed to make today's faulty, pain-in-the-ass code work.
/// <summary>
/// XAML markup extension to make it possible to reference nullable types.
/// </summary>
[MarkupExtensionReturnType (typeof (Type))]
public class NullableExtension : TypeExtension
{
/// <summary>
/// Initializes a new instance of the NullableExtension class.
/// </summary>
public NullableExtension ()
{}
/// <summary>
/// Initializes a new instance of the NullableExtension class, initializing the TypeName value based on the provided
/// typeName string.
/// </summary>
/// <param name="typeName">
/// A string that identifies the type to make a reference to. This string uses the format
/// prefix:className. prefix is the mapping prefix for a XAML namespace, and is only required to reference types that
/// are not mapped to the default XAML namespace.
/// </param>
public NullableExtension (string typeName)
: base (typeName)
{}
/// <summary>
/// Initializes a new instance of the NullableExtension class, declaring the type directly.
/// </summary>
/// <param name="type">The type to be represented by this NullableExtension.</param>
public NullableExtension (Type type)
: base (type)
{}
/// <summary>
/// Returns an object that should be set on the property where this extension is applied. For
/// <see cref="T:System.Windows.Markup.TypeExtension" /> , this is the <see cref="T:System.Type" /> value as evaluated
/// for the requested type name.
/// </summary>
/// <returns>
/// The <see cref="T:System.Type" /> to set on the property where the extension is applied.
/// </returns>
/// <param name="serviceProvider">
/// Object that can provide services for the markup extension. The provider is expected to
/// provide a service for <see cref="T:System.Windows.Markup.IXamlTypeResolver" />.
/// </param>
/// <exception cref="T:System.InvalidOperationException">Member value for the extension is null.</exception>
/// <exception cref="T:System.ArgumentException">
/// Some part of the typeName string did not parse
/// properly.-or-<paramref name="serviceProvider" /> did not provide a service for
/// <see cref="T:System.Windows.Markup.IXamlTypeResolver" />-or- typeName value did not resolve to a
/// type.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="serviceProvider" /> is null</exception>
public override object ProvideValue (IServiceProvider serviceProvider)
{
if (serviceProvider == null)
throw new ArgumentNullException ("serviceProvider");
var basis = (Type) base.ProvideValue (serviceProvider);
return typeof (Nullable<>).MakeGenericType (basis);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment