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

Xamarin中如何使用C#代码设置AppThemeBinding切换控件主题

错误原因

你之前的写法是直接将XAML标记字符串赋值给BackgroundColor属性,C#运行时不会自动解析XAML语法,因此无法生效。

正确实现方式

C#中需要通过AppThemeBinding类搭配SetBinding方法实现等效效果,完整代码如下:

// 1. 从全局资源中取出预先定义的明暗主题色
// 若资源定义在当前Page的Resources字典中,可替换为 this.Resources["资源名"]
Color lightBg = (Color)Application.Current.Resources["Body_Default_Background"];
Color darkBg = (Color)Application.Current.Resources["Body_Default_Background_Dark"];

// 2. 实例化AppThemeBinding对象,配置明暗对应值
AppThemeBinding bgThemeBinding = new AppThemeBinding
{
    Light = lightBg,
    Dark = darkBg
};

// 3. 给按钮的BackgroundColor属性绑定主题配置
button.SetBinding(Button.BackgroundColorProperty, bgThemeBinding);

如果需要在按钮点击时触发修改,将上述代码写入按钮的点击事件处理方法中即可。

注意:不要直接给BackgroundColor属性赋值固定Color值,使用绑定方式才能保证系统主题切换时,颜色会自动跟随更新。

内容的提问来源于stack exchange,提问作者joLee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:45:02