Uno Platform应用如何监听Android系统主题变更事件以更新自定义组件
Uno Platform 监听系统主题变更的实现方法
- 首选方案:直接订阅WinUI标准的
RequestedThemeChanged事件,Uno Platform全平台兼容该API,系统主题切换后应用回到前台时会自动触发该事件。
示例代码如下:// 在App初始化逻辑中添加订阅,比如App.xaml.cs的构造方法内 Application.Current.RequestedThemeChanged += (sender, args) => { // args.NewTheme 为切换后的主题枚举,可选值为 ApplicationTheme.Light / ApplicationTheme.Dark var currentTheme = args.NewTheme; // 在此处添加你自定义的组件更新逻辑 // 此时重新读取系统资源已为最新主题对应的值 var currentBaseHighColor = (Color)App.Current.Resources["SystemBaseHighColor"]; }; - 注意事项:如果你曾手动修改过
Application.Current.RequestedTheme为固定的浅色/深色值,需要先将其改回ApplicationTheme.Default,让应用跟随系统主题,RequestedThemeChanged事件才会正常触发。 - 低版本Uno兼容方案:如果你使用的Uno版本不支持上述事件,可以订阅应用窗口激活事件,每次应用回到前台时主动比对当前主题和缓存的历史主题,有差异时执行自定义逻辑:
private ApplicationTheme _lastCachedTheme; // 初始化时缓存初始主题 _lastCachedTheme = Application.Current.ActualTheme; Window.Current.Activated += (s, e) => { if (e.WindowActivationState != WindowActivationState.Deactivated) { var currentTheme = Application.Current.ActualTheme; if (currentTheme != _lastCachedTheme) { _lastCachedTheme = currentTheme; // 执行主题变更逻辑 var currentBaseHighColor = (Color)App.Current.Resources["SystemBaseHighColor"]; } } };
内容的提问来源于stack exchange,提问作者Stan V.
相关产品推荐
相关产品推荐

