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

.NET MAUI检查按钮背景色出现CS0120错误,如何解决?

.NET MAUI编译错误CS0120排查解决

问题代码

MainPage.xaml.cs

using System.ComponentModel;
using System.Windows.Input;
using Microsoft.Maui.Controls;

namespace App;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    // 省略其他代码

    private void LockerClicked(object sender, EventArgs e)
    {
        Button clickedButton = (Button)sender;

        if (clickedButton.BackgroundColor == Color.Blue)
        {
            // 执行操作
        }
    }
}

MainPage.xaml

<!-- 省略其他布局代码 -->
<Button x:Name="LockerButton" Clicked="LockerClicked" Text="⌨" Grid.Row="3" Grid.Column="2" FontSize="40" TextColor="#007070" FontAttributes="Bold" CornerRadius="100" BackgroundColor="White"/>
<!-- 省略其他布局代码 -->

编译错误信息

Compiler Error CS0120: An object reference is required for the nonstatic field, method, or property 'Color.Blue'

错误原因与解决方法

错误根源在于:.NET MAUI中Color是实例类,Blue是它的非静态属性,不能直接通过Color.Blue调用。正确的做法是使用静态类Colors(注意复数形式)来访问预定义颜色,它包含所有静态的颜色常量。

修改后的LockerClicked方法代码如下:

private void LockerClicked(object sender, EventArgs e)
{
    Button clickedButton = (Button)sender;

    if (clickedButton.BackgroundColor == Colors.Blue)
    {
        // 执行操作
    }
}

另外,如果你需要自定义颜色,也可以使用Color类的静态方法,比如Color.FromHex("#0000FF")、Color.FromRgb(0,0,255)等方式来创建颜色实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:33:23