我的标准 winform 上的应用按钮在加载时被禁用,如果任何其他控件的状态发生变化(复选框、单选框、文本框等),我想启用它
所以我可以遍历每个控件的事件并启用那里的按钮,但我想知道是否有更简单的方法来做到这一点,例如全局事件。
编辑 澄清一下:我正在寻找一种方法,无需对每个控件执行某些操作。这样我就可以在以后添加更多控件而不必关心它们......
最佳答案
根据您的编辑,我修改了我的答案以包含您想要的功能。
首先,您需要一个通用事件处理程序,应如下所示:
void MyHandler(object obj, EventArgs e)
{
button1.Enabled = true;
}
其中,button1 是您要启用的按钮。
那么你将需要一个递归方法来不仅迭代你的 Form.Controls
,但也包含其中的任何容器类型控件。我已经包含了一些常见容器控件以及一些基本数据输入控件的处理:
void AddEvents(System.Windows.Forms.Control.ControlCollection Controls)
{
foreach (Control c in Controls)
{
if (c is GroupBox)
{
AddEvents(((GroupBox)c).Controls);
}
else if (c is Panel)
{
AddEvents(((Panel)c).Controls);
}
//Expand this series of if...else... to include any
//other type of container control
else if (c is TextBox)
{
((TextBox)c).TextChanged += new EventHandler(MyHandler);
}
else if (c is RichTextBox)
{
((RichTextBox)c).TextChanged += new EventHandler(MyHandler);
}
else if (c is CheckBox)
{
((CheckBox)c).CheckedChanged += new EventHandler(MyHandler);
}
else if (c is DateTimePicker)
{
((DateTimePicker)c).ValueChanged += new EventHandler(MyHandler);
}
//Expand this to include any other type of controls your form
//has that you need to add the event to
}
}
第一部分if else
block 检查以查看 control
是否是包含其他控件的类型。如果是的话recursively使用新的 System.Windows.Forms.Control.ControlCollection
调用 AddEvents 方法包含在 control
.
第二部分if else
block 检查控制 c 是什么类型,以便可以适本地 cast正确的类型,从而利用正确的事件。如果此时我们能够确定控件类型,则之前创建的通用事件将被添加为处理程序。
最后,你需要调用这个方法。两个最好的地方可能是在你的构造函数中或在 Form.Load
上。事件。放置它的最佳位置取决于您的具体情况。为了简单起见,我选择使用构造函数,现在看起来像这样:
public Form1()
{
InitializeComponent();
AddEvents(this.Controls);
}
这应该是您迭代控件并添加通用事件处理程序所需的全部内容。该代码来 self 创建的实际项目,我已经对其进行了测试以确保其功能正常。
编辑:我也刚刚使用 control
对此进行了测试位于 GroupBox
内Panel
里面GroupBox
里面Panel
里面那是在Form
上。这就是利用递归的用处。只要正确设置if...else...
,您就不需要知道确切的嵌套深度。 block 。它将根据需要深入,而无需使用嵌套循环并知道确切的深度。
EDIT2:作为旁注,此方法也可以在更细粒度的级别上使用。假设您有多个 GroupBox
控件,并且您只想将事件处理程序添加到“grpBox1”中的控件。您可以调用AddEvents(grpBox1.Controls)
而不是AddEvents(this.Controls)
这只会将事件处理程序应用于 grpBox1
中包含的控件。 .
EDIT3: 正如 onemancat 在评论中指出的那样,并不完全有必要实际检查控件是否是 GroupBox
或Panel
等等,因为所有控件都继承自基类 Control
其中有 Controls
属性(property)。您只需检查 Control
是否包含其他控件,如 if (c.Controls.Count > 0) AddEvents(c.Controls);
但是,在想要选择要迭代的容器控件的情况下,有必要检查我在示例中的类型。如果不需要如此精细,那么检查计数确实更有意义,而不必费心进行类型检查或转换。
关于c# - 启用应用按钮的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14658074/