如何通过类访问表单控件? [英] How to access a form control through a class?

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

问题描述

我在VB.NET中进行编程,现在正在使用C#,对此我有些怀疑.在VB.NET中,当我将类添加到应用程序类型WindowsFormApliccation时,我可以使用窗体名称后跟所需控件名称的方式直接访问控件.
例如:我在表单上有一个文本框,并向项目中添加了一个类,在该类中,我具有以下方法.

I Program in VB.NET and I am now moving to C #, and I have some doubts. In VB.NET when I add a class to an application type WindowsFormApliccation I can access the controls directly, using the form name followed by the name of the control I want.
For example: I have a textbox on the form and add a class to the project, at the class I have the method below.

Public Class Class1
     Public Sub method ()
         Form1.TextBox1.Text = "text"
     end Sub
end Class



调用此方法时,它将在TextBox1中写入字符串"Text".我在C#中尝试了此操作,但未能成功.有人知道我该怎么做吗?



When this method is called it will write the string "Text" in TextBox1. I tried this in C # and could not. Does anyone know how I do it?

推荐答案

为什么要这样做(即使可行). IMO的正确方法是从表单中调用该类,并将文本框的内容发送给该类的方法.该方法还可以返回数据.因此,基本上您可以在表单代码中添加以下内容:
Why do it this way (even though it''s doable). IMO the proper way would be to call the class from the form and send the contents of the textbox to the method of the class. The method can also return data . So basically you could have in your form code like:
MyClass instance = new MyClass()
TextBox1.Text = instance.GetText();


和班级:


and the class:

public class MyClass {
   public string GetText() {
      return "text";
   }
}


根据情况,当不进行实例化时,类和方法也可以是静态的.

加法(不建议):

将形式作为参数传递,calss:


Depending on the situation the class and the method could also be static when no instantation would take place.

Addition (not advisable):

Passing the form as a parameter, the calss:

public class MyClass {
   public void SetText(Form1 formInstance) {
      formInstance.TextBox1.Text = "Text";
   }
}


并致电:


And calling:

MyClass instance = new MyClass()
instance.SetText(this);


Mika Wendelius是正确的.

我想在这里加2美分.
如果要使用c#访问表单,则可能需要这样做. Form1是在设计视图中创建的表单用户.
Mika Wendelius is right.

I would like to add my 2 cents here.
If you want to access a form in c# you may have to do. The Form1 is the form user created in design view.
Form1 f = new Form1();

然后通过实例"f"访问方法.

表单是容器类型.您不能直接访问表单上的控件.您必须使用f.Controls()方法.

开发人员通常需要从外部(也许从另一个类)访问特定的控件.但是,仅从外部将事件处理程序设置为控件是安全的,例如按钮单击事件.

then access the methods through instance "f".

The Form is a container type. You cannot directly access the controls on the form. You have to use f.Controls() method.

Often developers need to access a specific control from outside, maybe from another class. But, it is safe to set event handlers only to the controls from outside, for example button click event.


这篇关于如何通过类访问表单控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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