有以下幾種方法可以在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窗體傳值的方法,根據具體的需求選擇相應的方法。