从另一个类访问表单组件

coz*_*zzy 2 c# forms class

我希望标题和这个简单的例子说明一切.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void UpdateLabel(string str)
    {
        label1.Text = str;
       MessageBox.Show("Hello");
    }

    private void buttonIn_Click(object sender, EventArgs e)
    {
        UpdateLabel("inside");
    }

    private void buttonOut_Click(object sender, EventArgs e)
    {
        MyClass Outside = new MyClass();
        Outside.MyMethod();
    }
}

public class MyClass
{
    public void MyMethod()
    {
         Form1 MyForm1 = new Form1();
         MyForm1.UpdateLabel("outside");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我试图从MyClass更改lable1时,它什么也没做.但是我可以从外面看到UpdateLable方法,它对我说好,它只是不改变标签.

Mar*_*k H 6

使用代理人设置标签

public class MyClass {
    Action<String> labelSetter;

    public MyClass(Action<String> labelSetter) {
        this.labelSetter = labelSetter;
    }

    public void MyMethod() {
        labelSetter("outside");
    }
}
Run Code Online (Sandbox Code Playgroud)

.

public void buttonOut_Click(object sender, EventArgs e) {
    var outside = new MyClass(UpdateLabel);
    outside.MyMethod();
}
Run Code Online (Sandbox Code Playgroud)