Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a Resource dictionary and add another one in WPF

Tags:

wpf

xaml

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?

like image 803
sony Avatar asked Sep 13 '11 10:09

sony


1 Answers

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.

like image 82
WPF-it Avatar answered Nov 09 '22 06:11

WPF-it