.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
相关产品推荐
相关产品推荐

