C# 如何在UWP和WinUi中更改应用程序主题
我想更改我的UWP(WinUI2.5)应用程序主题,我使用了以下代码C# 如何在UWP和WinUi中更改应用程序主题,c#,uwp,winui,C#,Uwp,Winui,我想更改我的UWP(WinUI2.5)应用程序主题,我使用了以下代码 private void OnThemeRadioButtonChecked(object sender, RoutedEventArgs e) { var selectedTheme = ((RadioButton)sender)?.Tag?.ToString(); ApplicationViewTitleBar titleBar = ApplicationVi
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;
}
}
}
}
EmeradioButtonChecked上的私有无效(对象发送方,RoutedEventArgs e)
{
var selectedTheme=((RadioButton)sender)?.Tag?.ToString();
ApplicationViewTitleBar titleBar=ApplicationView.GetForCurrentView().titleBar;
if(selectedTheme!=null)
{
App.RootTheme=App.GetEnum(selectedTheme);
如果(已选择主题==“暗”)
{
titleBar.ButtonFourgroundColor=颜色.白色;
}
else if(选择主题==“灯光”)
{
titleBar.ButtonFourgroundColor=Colors.Black;
}
其他的
{
if(Application.Current.RequestedTheme==ApplicationTheme.Dark)
{
titleBar.ButtonFourgroundColor=颜色.白色;
}
其他的
{
titleBar.ButtonFourgroundColor=Colors.Black;
}
}
}
}
在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);
}
公共静态元素主题根主题
{
得到
{
if(Window.Current.Content是FrameworkElement根元素)
{
返回rootElement.RequestedTheme;
}
返回ElementTheme.Default;
}
设置
{
if(Window.Current.Content是FrameworkElement根元素)
{
rootElement.RequestedTheme=值;
}
}
}
公共静态TEnum GetEnum(字符串文本),其中TEnum:struct
{
if(!typeof(TEnum).GetTypeInfo().IsEnum)
{
抛出新的InvalidOperationException(“泛型参数'TEnum'必须是枚举”);
}
return(TEnum)Enum.Parse(typeof(TEnum),text);
}
但是,正如您所看到的,结果不是预期的,按钮在更改主题时有问题。我从Microsoft Xaml控件库示例项目中复制了代码
这是微软的一个很好的例子
安装并使用扩展
toolkit:TitleBarExtensions.ButtonBackgroundColor="Transparent"
toolkit:TitleBarExtensions.ButtonInactiveBackgroundColor="Transparent"