DEV Community

Rob
Rob

Posted on

What you don't know can't *help* you part 3; RequestedTheme

Dark is the new Light

As UWP developers, we are accustomed to our apps being displayed in both light and dark modes.

It still seems to be a Wow! Look at this! on other platforms, but we've been doing this for years.

The next level is enforcing a light or dark theme. You can set it by using the RequestedTheme property.

The most common use I've seen of this in the has been setting whole pages at once to one theme or another using the Page xaml like this:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    ...
    RequestedTheme="Dark">

This will set all controls within the Page XAML element to Dark theme. Which is cool because it shows us that it is inherited from parent controls

   <Page RequestedTheme="Dark">
       <TextBlock/> //Will be dark theme without us having to explicitly set it
       <Button/> //Will be dark theme without us having to explicitly set it
   </Page>

But wait, there's more!

So, how is it that it can apply to all these different elements like that?

Well, RequestedTheme is part of the FrameworkElement; which in UWP/Xaml is a very powerful base class used in (almost) every visual element you use daily.

Why is this important?

So?

Well, now that we know this we start to understand that we can use it in many more powerful ways.

For example, want to make it dark in your whole app, regardless of whether the user's OS is in dark mode or not?

Well, set it in App.xaml.cs!

<Application
    x:Class="My.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    ...
    RequestedTheme="Dark">

Or, you can go the other way and set it at the individual element level, by applying it to single FrameworkElements:

<Button
    Content="Press Me"
    TooltipService.Tooltip="I'm not saying the world will explode, but it might..."
    ...
    RequestedTheme="Dark"/>

...and any combnation of the above.

Namaste,
Rob.

Top comments (0)