There is some support for conditional compilation in XAML. It's not the same as in C#, code, though. The trick is to use AlternateContent
with Requires
against something flagged Ignorable. By doing this, you can actually have portions of your xaml unavailable based on conditions, and turn on or off.
I tried the other mentioned solution, and it compiles and works, even though Visual Studio will give you loads of errors, and for me the solution seems to use a lot of time on the UI thread, both of which I don't like.
The best solution I implemented instead was that I put all the conditional logic in the code behind of the control. As you don't mention your intention, this might be what you were looking for.
I wanted to have a conditional compilation symbol affect colors in my application, but you can also imagine the same solution to be used for other differing styles or even templates, or that this can be used with usual if-else logic instead of compilation symbols.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class ="MyApp.Style.MainStyle">
<!--Version1 -->
<Color x:Key="AbMainColor">#068C00</Color>
<Color x:Key="AbLighterMainColor">#5EBD50</Color>
<Color x:Key="AbDarkerMainColor">DarkGreen</Color>
<Color x:Key="MainColor" />
<Color x:Key="LighterMainColor" />
<Color x:Key="DarkerMainColor" />
<!-- Version2 -->
<Color x:Key="OtherRedColor">#EF0000</Color>
<Color x:Key="LighterRedColor">#e62621</Color>
<Color x:Key="DarkerRedColor">#EF0000</Color>
<SolidColorBrush x:Key="MainBrush" Color="{DynamicResource MainColor}" />
<SolidColorBrush x:Key="LighterMainBrush" Color="{DynamicResource LighterMainColor}" />
<SolidColorBrush x:Key="DarkerMainBrush" Color="{DynamicResource DarkerMainColor}" />
The code-behind for this can manually be created by placing a MainStyle.xaml.cs in your application and use it like this:
using System.Windows;
namespace MyApp.Style
{
partial class MainStyle : ResourceDictionary
{
public MainStyle()
{
InitializeComponent();
#if VERSION2
this["MainColor"] = this["OtherRedColor"];
this["LighterMainColor"] = this["LighterRedColor"];
this["DarkerMainColor"] = this["DarkerRedColor"];
#elif VERSION1
this["MainColor"] = this["AbMainColor"];
this["LighterMainColor"] = this["AbLighterMainColor"];
this["DarkerMainColor"] = this["AbDarkerMainColor"];
#endif
}
}
}
Important to note is that if reference only the unset values from my XAML code, and that this also works for StaticResource
s, although the constructor only gets called once. I guess overwriting / using more of the resource dictionaries methods would also work, but this already solved my problem so I didn't try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With