如何检测窗体的任何控件的更改? [英] How to detect changes in any control of the form?

查看:28
本文介绍了如何检测窗体的任何控件的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测 C# 中表单的任何控件的更改?

How can I detect changes in any control of the form in C#?

因为我在一个表单上有很多控件,如果表单中的任何控件值发生变化,我需要禁用一个按钮.我正在寻找一些内置函数/事件处理程序/属性,并且不想为此制作自定义函数.

As I have many controls on one form and i need to disable a button if any of the control value in the form changes. I am in search of some built-in function/event-handler/property, and don't want to make a customized function for that.

推荐答案

不,我不知道每当表单上的任何控件发生更改时会触发任何事件.

No, I'm not aware of any event that fires whenever any control on the form changes.

我的建议是单独订阅每个事件(如果您的表单有太多控件以至于这实际上很难做到,那么您可能需要重新考虑您的 UI).

My advice would be to subscribe to each event individually (if your form has so many controls that this is actually difficult to do, then you may want to re-think your UI).

如果您绝对必须订阅对所有控件的更改,那么您可能需要考虑类似于以下内容:

If you absolutely must subscribe to changes to all controls then you might want to consider something similar to the following:

foreach (Control c in this.Controls)
{
    c.TextChanged += new EventHandler(c_ControlChanged);
}

void c_ControlChanged(object sender, EventArgs e)
{

}

请注意,如果您在运行时动态地向表单添加和删除控件,这将不会特别好用.

Note that this wouldn't work particularly well however if you dynamically add and remove controls to the form at runtime.

此外,TextChanged 事件可能不适用于某些控件类型(例如文本框) - 在这种情况下,您需要转换和测试控件类型才能订阅到正确的事件,例如:

Also, the TextChanged event might not be a suitable event for some control types (e.g. TextBoxes) - in this case you will need to cast and test the control type in order to be able to subscribe to the correct event, e.g.:

foreach (Control c in this.Controls)
{
    if (c is CheckBox)
    {
        ((CheckBox)c).CheckedChanged += c_ControlChanged;
    }
    else
    {
        c.TextChanged += new EventHandler(c_ControlChanged);
    }
}

这篇关于如何检测窗体的任何控件的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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