Conditionally adding elements declared in XAML to the element tree

In my previous post I showed a markup extension that only creates elements declared in your XAML file if you are running with Full Trust from the CLR. After I posted that, Laurent Bugnion, a fellow WPF MVP and WPF Disciple (as well as a really great guy!), asked if I know of a way to use a markup extension to perform the moral equivalent of a #if … #elif … #endif in C#. That was an interesting question, so I decided to investigate. It turned out to be very simple.

Here is my new If class:

You can use that markup extension to conditionally add elements to the element tree, based on whether you are building a DEBUG or RELEASE build. Here is a demo of that class being used:

If you create a DEBUG build, the top TextBlock appears in the Window, otherwise the bottom TextBlock shows up. Naturally, if you have a more complicated set of build options, you can enhance my If class to take those build configurations into account.


After I posted this, Andrew Smith pointed out that there is another way to achieve this, as seen here.  The approach involves the use of the Markup Compatibility XML namespace, and another assembly to contain your own XML namespaces.  That technique is more complicated to set up, but the elements in excluded blocks will not be created/seen by the XAML reader.


Download the source code here. NOTE: Change the file extension from .DOC to .ZIP and then decompress it.

6 Responses to Conditionally adding elements declared in XAML to the element tree

  1. Sarafian Alex says:

    I never thought that this might be usefull, but now that I know there is a way probably I’ll come to use it someday.

    In my company we are now beginning a project with WPF, and I realy must thank you,Karl for your articles in your blogs.

    Thank you

  2. Josh Smith says:

    Thanks Sarafian, I’m glad you find them useful.

  3. marlongrech says:

    great one dude…. really really nice!

  4. Josh Smith says:

    thanks marlon! i appreciate your feedback.

  5. John "Z-Bo" Zabroski says:

    More useful and flexible would be public class Pragma : MarkupExtension { /** Stuff */ }

    This feels like “recursive descent Smalltalk” with If constructs as first-class objects, if that makes any sense. It also enables a limited form of multi-stage programming.

    Josh, I have to thank you a lot. I thought XAML was an awful language until I started reading what you have to say. I still feel XAML out-of-the-box has some shortcomings, like violating the Open-Closed Principle and promoting Pollution of the Knowledge Space. However, people like you have made it bearable to work with.

%d bloggers like this: