You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:06:02