Expose all event handlers of UserControl

给你一囗甜甜゛ 提交于 2019-12-02 10:56:40
Ben

So, if I understand correct, I think there are 2 ways you can proceed:

Approach 1

In the UserControl, set the Modifiers property of each textbox (or the ones you are interested in) to public:

Then in the Form that uses this UserControl you can access all these textboxes and hence their events:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        myUserControl1.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
    }
}

Approach 2 (Taken from this post)

You can create new events for your UserControl that simply pass forward the event of an underlying textbox. The underlying textboxes can then remain private to the UserControl.

In the UserControl add this event:

public event KeyEventHandler TextBox1KeyDown
{
    add { textBox1.KeyDown += value; }
    remove { textBox1.KeyDown -= value; }
}

Or you can create a single event that deals with all textboxes:

public event KeyEventHandler AnyTextBoxKeyDown
{
    add
    {
        textBox1.KeyDown += value;
        textBox2.KeyDown += value;
        textBox3.KeyDown += value;
        ...
    }
    remove
    {
        textBox1.KeyDown -= value;
        textBox2.KeyDown -= value;
        textBox3.KeyDown -= value;
        ...
    }
}

Now your UserControl has a event of its own that the code in the Form can use:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        myUserControl1.TextBox1KeyDown += new KeyEventHandler(myUserControl1_TextBox1KeyDown);
        myUserControl1.AnyTextBoxKeyDown += new KeyEventHandler(myUserControl1_AnyTextBoxKeyDown );
    }

    private void myUserControl1_TextBox1KeyDown(object sender, KeyEventArgs e)
    {
        /* We already know that TextBox1 was pressed but if
         * we want access to it then we can use the sender
         * object: */
        TextBox textBox1 = (TextBox)sender;

        /* Add code here for handling when a key is pressed
         * in TextBox1 (inside the user control). */
    }

    private void myUserControl1_AnyTextBoxKeyDown(object sender, KeyEventArgs e)
    {
        /* This event handler may be triggered by different
         * textboxes. To get the actual textbox that caused
         * this event use the following: */
        TextBox textBox = (TextBox)sender;

        /* Add code here for handling when a key is pressed
         * in the user control. */
    }
}

Note that while this approach keeps the textboxes private within the UserControl, they can still be accessed from the event handler by the sender argument.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!