将事件处理程序动态地添加到面板中的控件中

本文关键字:控件 添加 事件处理 程序 动态 | 更新日期: 2023-09-27 18:12:04

我有一个简单的类:

class MyPanel
{
    Panel p_panel;                     //declaring all the elements I need
    CheckBox cb_choice;
    RadioButton rb_nagy, rb_kicsi;
    TextBox tb_db;
    public Panel getPanel() {        
        create();                     //creating all the elements I need, then putting them all in the created Panel.
        customize();                  //setting the panel's size, and the other control's locations within the panel.
        return p_panel;               //so if I call this method from an other class, this method will return a panel with all the controls inside.

在另一个类中,我有一个面板列表,所有面板都是用上述方法创建的。布局完成了,它工作得很整齐,我可以在屏幕上添加任意数量的内容。但现在我想给这些控件添加一些功能。例如,我希望禁用所有单选按钮,除非复选框已启用。那么,如何向面板列表中的所有复选框添加检查更改事件呢?

将事件处理程序动态地添加到面板中的控件中

似乎你只是想知道如何动态地添加EventHandler s到你的控件!

可以这样做:

cb_choice.CheckedChanged += cb_choice_CheckedChanged;

或者如果你想更明确(两种方法都是一样的)。

cb_choice.CheckedChanged += new EventHandler(cb_choice_CheckedChanged);

并定义一个处理程序方法:

private void cb_choice_CheckedChanged(object o, EventArgs args)
{
    //add code to enable/disable radiobuttons
}