Monday, December 29, 2014

How to change app theme in WP8.1 at runtime

I have created a test project to verify changing theme at runtime, but it does not work as what I expect. Here is my code:


App.xaml



<Application
x:Class="AppThemeTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppThemeTest">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Style.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

Style.xaml



<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppThemeTest">
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="B" Color="Yellow"></SolidColorBrush>
<SolidColorBrush x:Key="F" Color="Blue"></SolidColorBrush>
</ResourceDictionary>

<ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="B" Color="Blue"></SolidColorBrush>
<SolidColorBrush x:Key="F" Color="Yellow"></SolidColorBrush>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>

MainPage.xaml:



<Page
x:Class="AppThemeTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppThemeTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
RequestedTheme="Light"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid>
<StackPanel Margin="19,40,19,0">
<Border BorderBrush="{StaticResource B}" BorderThickness="8" Margin="10">
<TextBlock Foreground="{StaticResource F}" FontSize="28" Text="Hello" Margin="10"/>
</Border>

<ToggleSwitch OnContent="Light" OffContent="Dark" IsOn="True" Toggled="ToggleSwitch_Toggled" Header="Change theme" />
</StackPanel>
</Grid>
</Page>



part of MainPage.xaml.cs



private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
{
if (this.RequestedTheme == ElementTheme.Light)
{
this.RequestedTheme = ElementTheme.Dark;
}
else
{
this.RequestedTheme = ElementTheme.Light;
}
}



The result is that: the theme of the page and the ToggleSwitch control can be changed successfully, but the Border and the TextBlock cannot, their style are specified by me in the Style.xaml. Then what's the problem?



No comments:

Post a Comment