WPF: XAML MarkupExtension as a Macro and Object Factory

A Visual Studio 2008 Solution with the complete code listing for this posting is attached.

The MarkupExtension in XAML opens up a world of opportunity to make XAML work the way you want it to. It reminds me somewhat of macros where we think of expanding the macro as substituting the macro for something else. If we consider that the MarkupExtension does nothing more than provide a value that is substituted for the MarkupExtension, it is very much like expanding a Macro.

Parameterised macros are extremely powerful as they do more than just save you typing, they can form a domain specific language. MarkupExtensions are stateful and you can set their state from XAML, leading to the idea that the substitution can be parameterised.

In this article I will demonstrate how to use a custom MarkupExtension as a macro or an object factory. The ideas will be applied to to a simple macro expansion case and the more pertinent case of creating a custom ValueConverter in a manner that is simpler than that provided by raw XAML.

WPF: Preserving Whitespace in XAML.

By default an XML parser will eat whitespace, which is very handy when you want to keep a neat indented structure. However there are many instances where whitespace is significant and must be preserved. The xml:space attribute is used to tell the XML parser how to treat white space in an Elements content.

It should be noted that the xml:space attribute will affect not only the element on which it is declared, but also all descendant elements until a new xml:space attribute is encountered. For this reason we try to use this attribute only where it is needed, and as close to the element that requires it.

The XAML parser supports the xml:space attribute and indeed does the right thing in terms of preserving whitespace. However there is a bug in the XAML parser that prevents us from declaring the attribute on the desired XML element in some situations.

This issue was discussed briefly in a thread I started at the MSDN forums and the most elegant solution is discussed here in more detail.


Subscribe to RSS - blogs