如何从设置弹出窗口中的控件更改元素的RequestedTheme?

时间:2014-06-09 05:35:14

标签: c# xaml windows-runtime themes resourcedictionary

我正在设置我的WinRT应用中的设置动态弹出选项,以便用户更改应用的主题。

在App.xaml文件中,我为明暗主题设置了不同的ResourceDictionaries。我可以使用以下代码从其设置文件中设置我的应用程序的所需主题(RootPage是包含所有元素的网格名称):

if ((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["Theme"] == "0")
{
    RootPage.RequestedTheme = Windows.UI.Xaml.ElementTheme.Light;
}
if ((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["Theme"] == "1")
{
    RootPage.RequestedTheme = Windows.UI.Xaml.ElementTheme.Dark;
}

但是,我希望能够动态更改主题。基本上,当用户从设置弹出窗口中选择所需主题时,我希望主题立即更改,而不是必须等待应用程序重新启动。

我尝试使用以下命令:

App.Current.RequestedTheme = Windows.UI.Xaml.ApplicationTheme.Light;

但是这会使应用程序崩溃System.NotSupportedException

我还尝试使用以下内容将主题设置为RootPage元素:

var MainPage = Windows.UI.Xaml.Window.Current.Content as MainPage;
MainPage.RootPage.RequestedTheme = Windows.UI.Xaml.ElementTheme.Light;

但我做错了,因为它引发了System.NullReferenceException

有没有人可以帮我解决如何在设置弹出窗口中更改控件元素的RequestedTheme?

2 个答案:

答案 0 :(得分:1)

使用StaticResource提供Windows 8主题资源,因此无法在运行时更新。

以某种方式做你想做的事我建议你阅读这篇博文post

答案 1 :(得分:0)

尝试在App.xaml.cs中的App构造函数中设置应用程序请求的主题。

喜欢这个

public App()
{
     Current.RequestedTheme = ApplicationTheme.Light;
     this.InitializeComponent();
     ...
     ...
 }