有以下几种方法可以在WinForm窗体之间传值:
public class Form2 : Form
{
private string value;
public Form2(string value)
{
this.value = value;
}
}
// 创建实例时传入值
var form2 = new Form2("Hello");
form2.Show();
public class Form2 : Form
{
public string Value { get; set; }
public void SetValue(string value)
{
this.Value = value;
}
}
// 访问属性或方法传递值
var form2 = new Form2();
form2.Value = "Hello";
form2.Show();
public class Form1 : Form
{
public static string Value;
}
// 设置静态变量的值
Form1.Value = "Hello";
// 访问静态变量的值
var value = Form1.Value;
// 设置值
Application.Properties["Value"] = "Hello";
// 获取值
var value = Application.Properties["Value"].ToString();
public class Form1 : Form
{
public event EventHandler<MyEventArgs> ValueChanged;
private void OnValueChanged(string value)
{
ValueChanged?.Invoke(this, new MyEventArgs(value));
}
}
public class Form2 : Form
{
public Form2()
{
var form1 = new Form1();
form1.ValueChanged += Form1_ValueChanged;
}
private void Form1_ValueChanged(object sender, MyEventArgs e)
{
var value = e.Value;
}
}
public class MyEventArgs : EventArgs
{
public string Value { get; }
public MyEventArgs(string value)
{
Value = value;
}
}
这些都是常用的WinForm窗体传值的方法,根据具体的需求选择相应的方法。