且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测窗体的任何控件的更改?

更新时间:2023-12-06 16:37:22

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

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);
    }
}