Windows Phone: How to Programmatically Change the Style of an Application

In my Windows Phone 8 app, I have some implicit styles defined in the xaml file in the location /Styles/DefaultStyles.xaml

I have a similar file, but with different colors, fonts, etc. defined in /Styles/GreenStyles.xaml .

I reference the default style file in my App.xaml as follows:

<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Styles/DefaultStyles.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> 

I want my application to switch its implicit styles from another stylesheet (GreenStyles) programmatically.

How can i achieve this?

**

UPDATE:

I managed to change the source of the resource dictionary as follows:

 ResourceDictionary style = App.Current.Resources.MergedDictionaries.ToList()[0]; string source = String.Format("/ApplicationName;component/Styles/GreenStyles.xaml"); style.Source = new Uri(source, UriKind.Relative); 

Note: the word component must be written so as to avoid exceptions.

Now I have a problem: only only Implicit styles (those that do not have the x: Key attribute) switch when the dictionary source changes.

any other style with the specified key and two times (with different attributes) in both files will not be displayed in the user interface.

so if i have these files: DefaultStyles.xaml:

  <Style x:Key="MainGrid" TargetType="Grid"> <Setter Property="Background" Value="Red"/> </Style> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontSize" Value="24"/> </Style> </ResourceDictionary> 

And: GreenStyles.xaml:

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"> <Style x:Key="MainGrid" TargetType="Grid"> <Setter Property="Background" Value="Green"/> </Style> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="Green"/> <Setter Property="FontSize" Value="24"/> </Style> </ResourceDictionary> 

and I switched the source to GreenStyles.xaml , any Grid with MainGrid style will still have a Red background.

What is the reason for this?

+4
source share
1 answer

You can try using the Jeff Wilcox approach described here: http://www.jeff.wilcox.name/2012/01/phonethememanager/

An alternative approach is described here for Silverlight, and I'm not sure if this will work on Windows Phone (although they share some code base): http://silverlightips.wordpress.com/2010/04/29/change-themestyle-using- merged-dictionaries /

Both methods are not easy if you have a large application and you can consider another option, for example (call me crazy)

 <Button Style="{Binding Locator.Theme, Converter={StaticResource StyleThemeConverter}, ConverterParameter=RefreshButtonStyle}" 

Hope this helps.

0
source

All Articles