I want to change my UWP (winui 2.5) App theme, I used the following code
private void OnThemeRadioButtonChecked(object sender, RoutedEventArgs e)
{
var selectedTheme = ((RadioButton)sender)?.Tag?.ToString();
ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;
if (selectedTheme != null)
{
App.RootTheme = App.GetEnum<ElementTheme>(selectedTheme);
if (selectedTheme == "Dark")
{
titleBar.ButtonForegroundColor = Colors.White;
}
else if (selectedTheme == "Light")
{
titleBar.ButtonForegroundColor = Colors.Black;
}
else
{
if (Application.Current.RequestedTheme == ApplicationTheme.Dark)
{
titleBar.ButtonForegroundColor = Colors.White;
}
else
{
titleBar.ButtonForegroundColor = Colors.Black;
}
}
}
}
and in App.xaml.cs
public static ElementTheme RootTheme
{
get
{
if (Window.Current.Content is FrameworkElement rootElement)
{
return rootElement.RequestedTheme;
}
return ElementTheme.Default;
}
set
{
if (Window.Current.Content is FrameworkElement rootElement)
{
rootElement.RequestedTheme = value;
}
}
}
public static TEnum GetEnum<TEnum>(string text) where TEnum : struct
{
if (!typeof(TEnum).GetTypeInfo().IsEnum)
{
throw new InvalidOperationException("Generic parameter 'TEnum' must be an enum.");
}
return (TEnum)Enum.Parse(typeof(TEnum), text);
}
But the result is not expected As you can see, the buttons have a problem with changing the theme I copied the code from Microsoft Xaml Controls Gallery sample project
and this is microsoft sample that work fine