我怎样才能确定事件被解雇由用户操作或code?事件、操作、用户、code

2023-09-05 02:15:42 作者:思念是噬心的痛

我有一大堆的控件在窗体上和他们所有的变事件指向同一个事件处理程序。其中有些是txtInput1的框TextChanged ,chkOption1的的CheckedChanged ,然后cmbStuff1的的SelectedIndexChanged 。这里是事件处理程序:

I have a bunch of controls on a form and all of their "change" events point to the same event handler. Some of these are txtInput1's TextChanged, chkOption1's CheckedChanged, and cmbStuff1's SelectedIndexChanged. Here is the event handler:

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语句,当用户改变文本框的文本或点击一个复选框或任何只需要运行。我不希望它发生,如果文本或复选框被程序的其它部分改变。

I would like the if statement to only run when a user changes the TextBox text or clicks a checkbox or whatever. I don't want it to happen if the text or checkbox was changed by some other part of the program.

推荐答案

没有一个内置的机制来做到这一点。你可以,但是,使用标志。

There isn't a built-in mechanism to do this. You can, however, use a flag.

bool updatingUI = false;

private void UpdatePreview(object sender, EventArgs e)
{
    if (updatingUI) return;

    txtPreview.Text = "The user has changed one of the options!";
}

然后,当你从你的code更新的用户界面:

Then, when you're updating the UI from your code:

updatingUI = true;

checkBox1.Checked = true;

updatingUI = false;

如果你想过度设计的解决方案,你可以使用这样的:

If you want to over-engineer the solution, you could use something like this:

private void UpdateUI(Action action)
{
    updatingUI = true;

    action();

    updatingUI = false;
}

和使用这样的:

UpdateUI(()=>
{
    checkBox1.Checked = true;
});