nothingIsNecessary 的答案非常接近,但我仍然需要环顾四周才能使其正常工作。
也就是说,问题是
AddOnChangeHandlerToInputControls(panelFormContainer);
应该
AddOnChangeHandlerToInputControls(this);
panelFormContainer 不起作用,我也找不到它的文档。
参考:循环遍历表单上的所有控件,甚至是组框中的控件
我还继续根据需要添加了更多控件类型。我将 MouseCaptureChanged 用于 datePicker,因为复选框有时会触发 ValueChanged,有时不会。¯_(ツ)_/¯
private void AddOnChangeHandlerToInputControls(Control ctrl)
{
foreach (Control subctrl in ctrl.Controls)
{
if (subctrl is TextBox)
{
((TextBox)subctrl).TextChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is CheckBox)
{
((CheckBox)subctrl).CheckedChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is RadioButton)
{
((RadioButton)subctrl).CheckedChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is ListBox)
{
((ListBox)subctrl).SelectedIndexChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is ComboBox)
{
((ComboBox)subctrl).SelectedIndexChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is MaskedTextBox)
{
((MaskedTextBox)subctrl).TextChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is DateTimePicker)
{
((DateTimePicker)subctrl).MouseCaptureChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is RichTextBox)
{
((RichTextBox)subctrl).TextChanged += new EventHandler(InputControls_OnChange);
}
else if (subctrl is NumericUpDown)
{
((NumericUpDown)subctrl).TextChanged += new EventHandler(InputControls_OnChange);
}
else
{
if (subctrl.Controls.Count > 0)
{
this.AddOnChangeHandlerToInputControls(subctrl);
}
}
}
}