我在表单上有一堆控件,所有"更改"事件都指向同一个事件处理程序.其中一些是txtInput1的TextChanged,chkOption1的CheckedChanged和cmbStuff1的SelectedIndexChanged.这是事件处理程序:
private void UpdatePreview(object sender, EventArgs e)
{
// TODO: Only proceed if event was fired due to a user's clicking/typing, not a programmatical set
if (sender.IsSomethingThatTheUserDid) // .IsSomethingThatTheUserDid doesn't work
{
txtPreview.Text = "The user has changed one of the options!";
}
}
Run Code Online (Sandbox Code Playgroud)
我希望if语句只在用户更改TextBox文本或单击复选框或其他任何内容时运行.如果文本或复选框被程序的其他部分更改,我不希望它发生.
没有内置机制来执行此操作.但是,您可以使用标志.
bool updatingUI = false;
private void UpdatePreview(object sender, EventArgs e)
{
if (updatingUI) return;
txtPreview.Text = "The user has changed one of the options!";
}
Run Code Online (Sandbox Code Playgroud)
然后,当您从代码更新UI时:
updatingUI = true;
checkBox1.Checked = true;
updatingUI = false;
Run Code Online (Sandbox Code Playgroud)
如果您想过度设计解决方案,可以使用以下内容:
private void UpdateUI(Action action)
{
updatingUI = true;
action();
updatingUI = false;
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
UpdateUI(()=>
{
checkBox1.Checked = true;
});
Run Code Online (Sandbox Code Playgroud)