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.