我可以分配给多个基于表单的事件的方法? [英] Can I assign a method to multiple Form-based Events?

查看:121
本文介绍了我可以分配给多个基于表单的事件的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建形式和它有几个控件的NumericUpDown,几个CheckBox控件以及一些文本框等每个控件都有所引发的事件方法(的CheckedChanged,等的ValueChanged),做的东西,但我的主要quesiton是这样的:

I'm constructing a Form and it has several numericUpDown controls, several checkbox controls and some text boxes etc. Each control has a event method (CheckedChanged, ValueChanged etc) that is triggered that does something but my main quesiton is this:

我想要做的就是运行,将更新的文本字段的窗体上,但目前我有它只是重复24次一个方法是什么。这工作,但我觉得必须有更好的方法...下面是我到目前为止的例子。

What I want to do is run a single method which will update a text field on my form but currently I have it just repeated 24 times. This works but I feel there must be a better way ... Below is an example of what I have so far.

    private void button3_Click(object sender, EventArgs e)
    {
    // Code Specific to the Buton3_Click
    UpdateTextLabel();
    }
    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
    // Code Specific to the checkBox1_CheckChanged
    UpdateTextLabel();
    }
    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
    // numericUpDown1 specific code ....
    UpdateTextLabel();
    }
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    // comboBox1 specific stuff ...
    UpdateTextLabel();
    }
   // .... and so on for every method ....

有没有更好的方式来实现这一目标?我想说:如果被点击或更改任何控制...这样做UpdateTextLabel()东西,但不知道如何去做。快乐被引导到答案,因为我键入搜索问题似乎并没有成为正确的问题...

Is there a better way to achieve this? I want to say "if any control is clicked or changed ... DO THIS "UpdateTextLabel()" thing " but not sure how to go about it. Happy to be directed to the answer as the questions I typed into search didn't seem to be the "right questions" ...

谢谢!

推荐答案

是的,你不希望这样写代码。你不必,该Application.Idle事件是理想的更新UI状态。它运行从消息队列中检索到的所有未决消息后的WinForms每次。所以保证之后的任何您当前订阅的事件来运行。使它看起来是这样的:

Yes, you don't want to write code like this. You don't have to, the Application.Idle event is ideal to update UI state. It runs every time after Winforms retrieved all pending messages from the message queue. So is guaranteed to run after any of the events you currently subscribe. Make it look like this:

    public Form1() {
        InitializeComponent();
        Application.Idle += UpdateTextLabel;
        this.FormClosed += delegate { Application.Idle -= UpdateTextLabel; };
    }

    void UpdateTextLabel(object sender, EventArgs e) {
        // etc..
    }

这篇关于我可以分配给多个基于表单的事件的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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