我怎样才能确定事件被解雇由用户操作或code? [英] How can I determine if an event was fired by a user action or by code?

查看:93
本文介绍了我怎样才能确定事件被解雇由用户操作或code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大堆的控件在窗体上和他们所有的变事件指向同一个事件处理程序。其中有些是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;
});

这篇关于我怎样才能确定事件被解雇由用户操作或code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆