开发者

Exposing events of underlying control

开发者 https://www.devze.com 2023-01-08 05:02 出处:网络
I have a combobox in a custom control. How can I expose specific events from it such as SelectedIndexChanged or KeyPress, etc t开发者_如何学Goo anyone/thing implementing my custom control?You can forw

I have a combobox in a custom control. How can I expose specific events from it such as SelectedIndexChanged or KeyPress, etc t开发者_如何学Goo anyone/thing implementing my custom control?


You can forward the events like this:

    public event EventHandler SelectedIndexChanged 
    {
        add { inner.SelectedIndexChanged += value; }
        remove { inner.SelectedIndexChanged -= value; }
    }


You will need to code these into the control yourself - the user control does not automatically promote the events of its child controls. You can then cross-wire your actual control to the user control's promoted event:

        public event EventHandler SelectedIndexChanged;

        private void OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (SelectedIndexChanged != null)
                SelectedIndexChanged(sender, e);
        }

        public UserControl1()
        {
            InitializeComponent();

            cb.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);
        }

Unfortunately you will need to do this for every event you are interested in.


A very simple solution rather than having custom events, would be to expose the nested control as a property of the custom control. From there you could attach event handlers to it very easily. It is not always advisable to expose child controls, but depending on the control type and how you are using it, it may work.

//create an instance of my control
MyCustomControl controlInstance = new MyCustomControl();

//attach and event handler to the exposed subcontrol
controlInstance.SaveButton.Click += new EventHandler(SaveButton_Click);


There is another way to handle that through the designer :

On the designer, in your custom control, on the combobox property under "Design" set "Modifiers" to internal.

Then where you need to to do something about it add :

CustControlName.YourCombo.SelectedIndexChanged += YourCombo_SelectedIndexChanged;

along with :

private void YourCombo_SelectedIndexChanged(object sender, EventArgs e)
{ 
    // Code to execute when the SelectedIndexIsChanged goes here
}
0

精彩评论

暂无评论...
验证码 换一张
取 消