使用 C++ 更改应用程序主题

Change application theme with C++

我正在尝试实现一个设置页面(使用 XAML 和 C++),其中包含三个单选按钮:“Light”、“Dark”和“Use system theme”。 Application.RequestedTheme 怎么办?谢谢!

基于这个document关于Application.RequestedTheme,它提到

The theme can only be set when the app is started, not while it's running. Attempting to set RequestedTheme while the app is running throws an exception (NotSupportedException for Microsoft .NET code). If you give the user an option to pick a theme that's part of app UI, you must save the setting in the app data and apply it when the app is restarted.

因此您可以将主题的设置保存在应用程序数据中,并在您重新启动应用程序时将其应用到应用程序的构造函数中。例如:

App.xaml.cpp:

App::App()
{
    InitializeComponent();
    Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);

    auto value = Windows::Storage::ApplicationData::Current->LocalSettings->Values->Lookup(L"themeSetting");
    if (value != nullptr)
    {
        String^ colorS = safe_cast<String^>(value);
        // Apply theme choice.
        if (colorS == L"Dark") {
            App::Current->RequestedTheme = ApplicationTheme::Dark;
        }
        else {
            App::Current->RequestedTheme = ApplicationTheme::Light;
        }
    }
}

Setting.xaml.cpp:

void AppCX::BlankPage::Light_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    Windows::Storage::ApplicationData::Current->LocalSettings->Values->Insert(L"themeSetting", ApplicationTheme::Light.ToString());
}


void AppCX::BlankPage::Dark_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    Windows::Storage::ApplicationData::Current->LocalSettings->Values->Insert(L"themeSetting", ApplicationTheme::Dark.ToString());
}

void AppCX::BlankPage::UseSystemTheme_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    auto DefaultTheme = ref new Windows::UI::ViewManagement::UISettings();
    auto uiTheme = DefaultTheme->GetColorValue(Windows::UI::ViewManagement::UIColorType::Background).ToString();
    
    if (uiTheme == Windows::UI::Colors::Black.ToString()) {
        Windows::Storage::ApplicationData::Current->LocalSettings->Values->Insert(L"themeSetting", ApplicationTheme::Dark.ToString());
    }
    else if (uiTheme == Windows::UI::Colors::White.ToString())
    {
        Windows::Storage::ApplicationData::Current->LocalSettings->Values->Insert(L"themeSetting", ApplicationTheme::Light.ToString());
    }
}