I have two resource dictionaries. One is called ResDictGlass.xaml and the other ResDictNormal.xaml. Both has identical properties and different values. For instance
ResDictGlass.xaml has one style like this:
<Style x:Key="StyleTitleText" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Arial" />
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="Green" />
</Style>
The same style in ResDictNormal.xaml is:
<Style x:Key="StyleTitleText" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Tahoma" />
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="WhiteSmoke" />
</Style>
I set up the textblock in the xaml as:
<TextBlock Style="{DynamicResource StyleTextblock}" Text="Prod.Code" VerticalAlignment="Top" />
I want to switch between these styles at runtime. What I do is like this:
case "normal":
ResourceDictionary ResDict1 = new ResourceDictionary();
ResDict1.Source = new Uri("/ResDictNormal.xaml", UriKind.RelativeOrAbsolute);
Application.Current.Resources.MergedDictionaries.Add(ResDict1);
break;
case "flip":
ResourceDictionary ResDict2 = new ResourceDictionary();
ResDict2.Source = new Uri("/ResDictGlass.xaml", UriKind.RelativeOrAbsolute);
Application.Current.Resources.MergedDictionaries.Add(ResDict2);
break;
Is this the right approach? Do we have to remove the current dictionary and then add the dictionary?
Yes you would want to have either of the two dictionaries merged in the app and not both. Otherwise ambiguous resourecs will throw error upon their reference.
Also remember that you may need to use DynamicResource
over StaticResource
if the themes need to update the UI dynamically (i.e. withoput entire UI reloading).
Let me know if this helps.
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