[英]Passing values from form to function in other class then call function in form
我有一个表单和一个 class。在表单中,我有一个文本框和一个空的 label。用户应该在文本框中键入内容然后按下按钮。 我希望将文本框值和空 label 传递给 class,其中我有一个 function,它将文本框中的任何值传递给 label,然后再次清空文本框。 当我在文本框中键入内容并单击按钮时,没有任何反应。 这基本上就是我所拥有的。
形式:
public partial class Form1 : Form
{
private Class _class;
public Form1()
{
InitializeComponent();
_class = new Class();
}
public string TextBox
{
get { return TextBox1.Text; }
set { TextBox1.Text = value; }
}
public string Label
{
get { return Label1.Text; }
set { Label1.Text = value; }
}
private void btn1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != string.empty)
{
_class.Function();
}
else
{
Something else
}
}
}
Class:
class Class
{
public void Function()
{
using (var form = new Form1())
{
string TextBox = form.TextBox;
string Label = form.Label;
if (Label == string.Empty)
{
Label = TextBox;
TextBox = string.Empty;
}
else
{
Something else
}
}
}
}
为了修改您当前的表单,您需要将 object 传递给 function,每次调用 function 时都创建一个新表单是不正确的。 所以我猜你正在尝试做这样的事情:
public partial class Form1 : Form {
private Class _class;
public Form1()
{
InitializeComponent();
_class = new Class();
}
public string TextBox
{
get { return TextBox1.Text; }
set { TextBox1.Text = value; }
}
public string Label
{
get { return Label1.Text; }
set { Label1.Text = value; }
}
private void btn1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != string.Empty)
{
_class.Function(this);
}
else
{
//Something else
}
}
Class:
class Class {
public void Function(Form1 form)
{
string TextBox = form.TextBox;
string Label = form.Label;
if (Label == string.Empty)
{
Label = TextBox;
TextBox = string.Empty;
}
else
{
//Something else
}
}
无论如何,有更好的方法来修改 Forms 控件的属性。 您应该看一下 PropertyBinding ,它可以让您将 class 的属性与控制表单绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.