因为需要用到窗口通信,想到了用委托实现,下面介绍一种简单的委托实现方式(一个窗口中创建了另一个窗口)。
本例中为在form2中修改数据,当点击提交按钮时,form1自动修改为form2中填写的数据。
自定义事件类如下:
public class MyEventArgs : EventArgs
{
private MyData m_myData;
public MyData Commit{ get { return m_myData; } }
public MyEventArgs(MyData myData)
{
m_myData = myData;
}
}
其中MyData为自己定义的全局数据管理类,下同。
form2类如下:
public partial class form2: Form
{
public delegate void CommitData(object sender, MyEventArgs e);
public event CommitData getData;
public GameConfigWindow()
{
InitializeComponent();
}
private void commitButton_Click(object sender, EventArgs e)
{
MyData.GetInstace().GameId = int.Parse(gameIDText.Text);
MyData.GetInstace().RedFlag = redFlagText.Text;
MyEventArgs E = new MyEventArgs(MyData.GetInstace());
getData(this, E);
this.Close();
}
}
form1类定义如下:
public partial class form1: Form
{
public MainWindow()
{
InitializeComponent();
}
private void form2Button_Click(object sender, EventArgs e)
{
Form2 form2= new Form2();
form2.getData += new form2.CommitData(form2_commit);
form2.ShowDialog();
}
private void form2_commit(object sender, MyEventArgs e)
{
redFlag.Text = e.Commit.RedFlag;
gameIdlabel.Text = e.Commit.GameId.ToString().PadLeft(4, '0');
}
}