Wednesday, March 09, 2011

Creating a Custom Markup Extension in WPF (and soon, Silverlight)

WPF currently, and Silverlight in v5, enables you to create your own custom markup extensions. Markup extensions are those little strings in XAML that are typically (but not always) enclosed in {curly braces} which, as the name implies, add new functionality to XAML. The most commonly used markup extensions are the {StaticResource}, {TemplateBinding}, and {Binding} extensions. Creating your own markup extensions is a nice way to integrate your view of the world into the toolset. They're particularly popular with MVVM and similar toolkits.

This article is, in part, an excerpt from early work in Silverlight 5 in Action, the revised edition of Silverlight 4 in Action. SL5 in Action is due out by the end of 2011, and will have a MEAP (early access bits) around the time of the first public developer release of Silverlight 5.

Creating a Simple Markup Extension

There's not much ceremony to creating a markup extension. The amount of effort required is directly proportional to the complexity of what you're trying to do. For example:

public class HelloExtension : MarkupExtension
{
  public HelloExtension() { }
  public override object ProvideValue(
                  IServiceProvider serviceProvider)
  {
    return "Hello";
  }
}

As shown in this example, to create a markup extension, you need only inherit from MarkupExtension and override the ProvideValue method. The empty constructor is necessary for use in XAML, specifically when you include additional parameterized constructors. When you use the markup extension, you must declare the namespace as explained in section 2.1.2 (of Silverlight 4/5 in Action), and use the class name in your XAML. For example, the following XAML uses the HelloExtension markup extension we just created.

<Grid xmlns:ext="clr-namespace:CustomMarkupExtensions">
  <TextBlock Text="{ext:Hello}" />
</Grid>

Read more: 10Rem.NET