我在一个表单上有一堆控件,它们所有的“更改”事件都指向同一个事件处理程序。其中一些是 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!";
}
}
我希望 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!";
}
然后,当您从代码更新 UI 时:
updatingUI = true;
checkBox1.Checked = true;
updatingUI = false;
如果你想过度设计解决方案,你可以使用这样的东西:
private void UpdateUI(Action action)
{
updatingUI = true;
action();
updatingUI = false;
}
然后像这样使用它:
UpdateUI(()=>
{
checkBox1.Checked = true;
});
关于c# - 如何确定事件是由用户操作还是代码触发的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3103912/