从另一个类文件访问MainForm [英] Accessing MainForm from another class file

查看:194
本文介绍了从另一个类文件访问MainForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个MainForm类:

I have this MainForm class:

namespace homework_001{

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

    public string Change
    {
        get{ return label.Text;}
        set{ label.Text = value;}
    }

     void ButtonClick(object sender, EventArgs e)
    {
        Test a = new Test();
        a.changer();


    }
}}

有这个类:

namespace homework_001{

public class Test
{       
    private MainForm form = new MainForm ();
    public void changer(){
    form.Change = "qqqqq!";
    }
}}

想要的工作流程是更改标签/按钮按下。

Desired workflow is to change the label/text on button press. It compiles, but nothing happens after I press the button.

这可能是什么问题?

推荐答案

发生的是你所显示的窗体与类 Test 中的窗体不同。

What is happening is that the form you are showing is not the same as the one inside the class Test.

要使事情生效,您应该以这种方式将表单传递给 Test 类:

To make things work you should pass the form to the class Test in this way:

public class Test
{       
    private MainForm form;
    public Test(MainForm f)
    {
        this.form=f;
    }
    public void changer(){
    form.Change = "qqqqq!";
    }
}}

并且在主窗体中: / p>

and in your main form you do this:

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

    public string Change
    {
        get{ return label.Text;}
        set{ label.Text = value;}
    }

     void ButtonClick(object sender, EventArgs e)
    {
        Test a = new Test(this);
        a.changer();


    }
}}

这篇关于从另一个类文件访问MainForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆