Bitesized tidbits for building Modern (Metro) apps.
Windows 8.1 and Windows Phone 8.1 both have this really great theme support that allows you to use ThemeResource as a xaml type, it means if the theme changes, anything using that will change its theme too. It’s actually very cool. What’s not cool though is you can only have two themes (Light/Dark). What if you want other themes? Yes, you can override both of those themes to show your own custom theme, but what if you want a third? A fourth? What then?
Well I’ve created a little helper that helps to alleviate that, and also means that you can swap themes on the fly without having to restart the app. Pretty cool, huh.
The solution is actually stupidly simple, that sort of makes you wonder why this just couldn’t have been included as part of the SDK, but hey.
So install the package from nuget: ThemeManagerRt
Once it’s installed, there are few things you need to configure before you can just start using it. These are things that could be done by a smarter person than me using powershell in the nuget package (subtle hint: someone help me with that please ).
In your App.xaml:
The thing to note in here is this resource *MUST* be named ThemeManager, the ThemeEnabledPage relies on it. If you don’t I will throw an exception and make you!
In there, you’ll also need to define a theme resource (you don’t have to, but the experience could be jarring for the user), and be sure to set the Dark theme:
<ResourceDictionary.ThemeDictionaries> <ResourceDictionary x:Key="Dark"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/Themes/Dark.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </ResourceDictionary.ThemeDictionaries>
On each page that needs to be theme enabled, instead of using Page as the page’s type, use ThemeEnabledPage. If you’re using a base page for your app, be sure that the base page inherits from ThemeEnabledPage.
When you want to change the theme, from viewmodel or wherever, just call:
And your theme will change. It will even have changed it for any pages that are in the backstack, so you get a full, app-wide theme change.
Want to see behind the scenes, pop over to Github and check out the source.