假设我有一个Checkbox控件:
CheckBox cb = new CheckBox();
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
MessageBox.Show("hello");
};
如何以编程方式触发此事件?
我能做到
cb.Checked = !cb.Checked;
cb.Checked = !cb.Checked;
但这很丑,会触发两次......
答案 0 :(得分:3)
我会重构你的代码:
CheckBox cb = new CheckBox();
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
ShowMessageBox();
};
private void ShowMessageBox()
{
MessageBox.Show("hello");
}
现在,请致电ShowMessageBox
,而不是尝试模拟事件。将您需要的任何信息从事件传递给方法,以防它需要更多来执行其任务:
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
ShowMessageBox(cb.Checked);
};
private void ShowMessageBox(bool checkedValue)
{
MessageBox.Show(string.Format("The box was {0}checked",
checkedValue ? "" : "un"));
}