简体   繁体   English

C#无法从另一个类更改窗体的组件

[英]C# Unable To Change Components Of Form From Another Class

Before I start, I'd like to say that I have looked for an answer for this over the internet for quite a while, and unable to come to a solution. 在开始之前,我想说的是,我已经在互联网上寻找答案了很长时间,并且无法找到解决方案。 I know how to solve this, but it doesn't want to work. 我知道如何解决此问题,但它不起作用。

Here's what I know: Assuming that I have a label and another class, if I want to manipulate the label I need to create an instance of the form that has the label, call the method of the new class with the form, and then call the method from within the form class that changes the label. 这就是我所知道的:假设我有一个标签和另一个类,如果我想操纵标签,我需要创建一个带有标签的表单的实例,用该表单调用新类的方法,然后调用更改标签的表单类中的方法。 This is what I have. 这就是我所拥有的。

This is from the form class 这是来自表单类

    private void button1_Click(object sender, EventArgs e)
    {
        Question steve = new Question(1, 1, "nothing", new string[] {});
        steve.Show(new Form1(), "I win");
    }

    public void ChangeLabel(string s)
    {
        this.lblTest.Text = s;
    }

And this is the Question class 这是Question类

    public void Show (Form1 f, string str)
    {
        f.ChangeLabel(str);
    }

Syntax-wise this is correct, and when running the debugger lblTest.Text did equal "I win", but there were no visual changes on the form. 从语法上讲,这是正确的,并且在运行调试器lblTest.Text时,其效果等同于“我赢了”,但是窗体上没有任何视觉变化。

PS I am in high school and still learning C#, so if I made any mistakes in my explanation or the code, please point them out. PS:我在读高中,还在学习C#,因此,如果我在解释或代码中有任何错误,请指出。 Also, disregard the Question constructor, it's useless right now. 另外,不管Question构造函数,它现在都没有用。

Thanks 谢谢

No ! 不行 you don't need to create new instance of the form. 您无需创建表单的新实例。

You must pass the current instance using this keyword: 您必须使用this关键字传递当前实例:

private void button1_Click(object sender, EventArgs e)
{
    Question steve = new Question(1, 1, "nothing", new string[] {});
    steve.Show(this, "I win");    //change it
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM