如何从另一个类访问 Winform 文本框控件? [英] How to access Winform textbox control from another class?

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

问题描述

我有一个 winform 叫做 Form1 和一个 textbox 叫做 textBox1

I have a winform called Form1 and a textbox called textBox1

Form1 中,我可以输入以下内容来设置文本:

In the Form1 I can set the text by typing:

textBox1.text = "change text";

现在我创建了另一个类.我如何在这个类中调用 textBox1 ?所以我想更改这个类中 textBox1 的文本.

Now I have created another class. How do I call textBox1 in this class? so I want to change the text for textBox1 in this class.

如何从这个新类访问 Form1?

How can I access the Form1 from this new class?

推荐答案

我建议您不要这样做.您真的想要一个依赖于如何在表单中实现文本编辑的类,还是想要一种允许您获取和设置文本的机制?

I would recommend that you don't. Do you really want to have a class that is dependent on how the text editing is implemented in the form, or do you want a mechanism allowing you to get and set the text?

我建议后者.因此,在您的表单中,创建一个包含相关 TextBox 控件的 Text 属性的属性:

I would suggest the latter. So in your form, create a property that wraps the Text property of the TextBox control in question:

public string FirstName
{
    get { return firstNameTextBox.Text; }
    set { firstNameTextBox.Text = value; }
}

接下来,创建一些机制,通过该机制您的类可以获取对表单的引用(例如通过构造函数).然后该类可以使用该属性访问和修改文本:

Next, create some mechanism through which you class can get a reference to the form (through the contructor for instance). Then that class can use the property to access and modify the text:

class SomeClass
{
    private readonly YourFormClass form;
    public SomeClass(YourFormClass form)
    {
        this.form = form;
    }

    private void SomeMethodDoingStuffWithText()
    {
        string firstName = form.FirstName;
        form.FirstName = "some name";
    }
}

一个更好的解决方案是在接口中定义可能的交互,并让该接口成为您的表单和其他类之间的契约.这样,类就与表单完全分离,并且可以使用任何实现接口的方法(这为更容易的测试打开了大门):

An even better solution would be to define the possible interactions in an interface, and let that interface be the contract between your form and the other class. That way the class is completely decoupled from the form, and can use anyting implementing the interface (which opens the door for far easier testing):

interface IYourForm
{
    string FirstName { get; set; }
}

在您的表单类中:

class YourFormClass : Form, IYourForm
{
    // lots of other code here

    public string FirstName
    {
        get { return firstNameTextBox.Text; }
        set { firstNameTextBox.Text = value; }
    }
}

...和班级:

class SomeClass
{
    private readonly IYourForm form;
    public SomeClass(IYourForm form)
    {
        this.form = form;
    }

    // and so on

}

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

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