问题
Ok, so I have a method in one class and I'm trying to call it from another class.
Form1:
public void ChangeBack(Color clr)
{
this.BackColor = clr;
}
Form2:
public void ChangBackColor_Click(object sender, EventArgs e)
{
if (ColorDialog.ShowDialog() == DialogResult.OK)
{
Form1.ChangeBack(ColorDialog.Color);
}
}
But I need to make the ChangeBack method static to be able to call it. So:
Form1:
public static void ChangeBack(Color clr)
{
this.BackColor = clr;
}
But then I can't use "this." as the void doesn't allow it because it's static. And I can't create a new form1 because it needs to run overall in two windows.
Please help!C
回答1:
When you are working with multiple forms, you need to pass a reference to the second form, so that it "knows" about the first form. To do this you will need to change the constructor of your second form, and add a private reference to that form, like so:
class Form2 : Form
{
//Variables
private Form1 _ParentForm; //Add this here
//Constructor
public Form2(Form1 parentForm)
{
InitalizeComponent();
_ParentForm = parentForm; //Add this here
}
}
The, when you create the second form on your main form, you can use this to pass the reference of itself on to the new form:
class Form1 : Form
{
public void ChangeBack(Color clr) //No longer needs to be static
{
this.BackColor = clr;
}
public void CreateSecondForm()
{
Form2 secondForm = new Form2(this);
secondForm.Show();
}
}
Then you can call any function on the parent form (i.e. Form1) from the second form like so:
public void ChangBackColor_Click(object sender, EventArgs e)
{
if (ColorDialog.ShowDialog() == DialogResult.OK)
{
//Access Form1's reference with _ParentForm instead of Form1
_ParentForm.ChangeBack(ColorDialog.Color);
}
}
回答2:
If you work with 2 different WinForm windows you should simply pass a reference from one window to the other (typically using constructor). For instance:
var childForm = new ChildForm(this); // where this is your main WinForm
after that you can use the reference to the main WinForm to call it's methods.
回答3:
That's correct, you cannot make the method static and access instance of the object.
Change BackColor to a static property or change your method to a non static one
来源:https://stackoverflow.com/questions/33193504/c-sharp-call-a-method-from-a-different-form-class