[英]Changing the BackColor of a Windows Form
Why can't I change the backcolor of my form this way? 为什么不能以这种方式更改表单的背景色?
MainForm.BackColor = System.Drawing.Color.Black;
This is what I get in the console: 这是我在控制台中得到的:
An object reference is required for the non-static field, method, or property 'System.Windows.Forms.Control.BackColor.get' (CS0120)
You're using MainForm as if it were a static class. 您正在使用MainForm,就好像它是静态类一样。 Either make your form static or create an instance of it.
使您的表单静态或创建它的实例。
MainForm form = new MainForm();
Then use 然后使用
form.BackColor = Color.Black;
Adding to the comment to your question, stick 为您的问题添加评论,坚持
this.BackColor = Color.Black;
inside of a method of your form, and just call that method. 在您的表单方法中,然后调用该方法。 Like so.
像这样
void changeBackColor(Color color)
{
this.BackColor = color;
}
That will let you pass a color to the method and changes the BackColor accordingly. 这样您就可以将颜色传递给方法,并相应地更改BackColor。
Hope this helps. 希望这可以帮助。 I'd recommend reading a book about C#.
我建议您读一本有关C#的书。 Objects can't be used before being initialized.
在初始化之前不能使用对象。 It's a pretty elementary concept.
这是一个非常基本的概念。
Static Classes are classes that cannot be instantiated. 静态类是无法实例化的类。 Static classes have static methods or static properties (or both).
静态类具有静态方法或静态属性(或两者)。 When you use a line like this:
当您使用这样的一行时:
MainForm.BackColor = System.Drawing.Color.Black; // <class name>.<property>
What the C# compiler does first is look for a local class variable called MainForm
. C#编译器首先要做的是寻找一个称为
MainForm
的局部类变量。 Since there was none, it then looked outside your local scope and found your Windows.Form
class called MainForm
. 由于没有任何内容,因此它会在您的本地范围之外,并找到名为
MainForm
的Windows.Form
类。
It then looked to see if the class MainForm
has a static property called BackColor
. 然后,它查看类
MainForm
是否具有称为BackColor
的静态属性。 The compiler then said "Oh look, there is a property called BackColor
, but its not static", which is when the compiler complained and threw you the error you experienced. 编译器然后说:“哦,有一个名为
BackColor
的属性,但它不是静态的”,这是编译器抱怨并将您遇到的错误扔给您时。
By changing it to this.BackColor
, the compiler knew you wanted to set the background color OF THIS INSTANCE of MainForm, which was this
or, by default, form1
: 通过将其更改为
this.BackColor
,编译器知道您要设置MainForm的背景色,即MainForm的背景色,即this
或默认为form1
:
this.BackColor = System.Drawing.Color.Black; // <this instance>.<property>
And as a side note, the keyword this
is not required. 另外,关键字
this
并非必需。 Omitting it assumes "this object". 忽略它会假定“此对象”。 You can do this just as well:
您也可以这样做:
BackColor = System.Drawing.Color.Black; // <this instance>.<property>
Hope this makes more sense! 希望这更有意义!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.