Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change ThemeResource/StaticResource or other in Win8 XAML app at runtime?

I have a windows 8.1 XAML application. I want to allow users to customize the theme of the app themselves - for example, I want to give them a color picker where they can set various colors in the app, which would set various resources used across my app.

The issue though, is I cant find out how to dynamically change the value of a resource. I know in 8.1 they added the concept of a theme resource, which allows me to change from light to dark theme at runtime and what not. But my issue is that I'd like to say 'the backgroundColor resource is now going to be orange, and all items using this resource will reflect this change'

I believe the DynamicResource XAML element is what I needed, but that seems to be from WPF and not supported in Win8. Does anyone have suggestions?

like image 664
Steve Avatar asked Dec 26 '13 21:12

Steve


2 Answers

It's only possible to change the Color of a SolidColorBrush, using:

(Application.Current.Resources["BackgroundBrush"] as SolidColorBrush).Color = Colors.Orange;

It's because SolidColorBrush is a class, all elements have a reference to it, changes its property will reflect to all elements. But Color is a struct so changes XXXColor won't work.

I only tested it on Windows Phone Runtime 8.1 APP, but it should also work for Windows Runtime 8.1 APPs.

like image 193
yume_chan Avatar answered Oct 18 '22 11:10

yume_chan


All the application resources are stored in the

Application.Current.Resources

dictionary. This dictionary can be inserted into by your code at run time. You need to do it at start up as any xaml page referencing a resource that doesn't exist will crash. Also once it's been referenced via a StaticResource extension it can't really be modified.

What I'd suggest doing is in your application start up code is detecting the theme the user wants and initializing the resource dictionary with the colors and brushes for that theme.

Application.Current.Resources["HighlightThemeBrush"] = new SolidColorBrush(255, 168,  243, 108);

If the user wants to change the theme then store it in settings and notify the user it will be changed when they restart the app. You'll notice that it's a very common pattern amongst apps that have custom themes.

like image 36
Nigel Sampson Avatar answered Oct 18 '22 09:10

Nigel Sampson