简体   繁体   中英

C# Get Events of a Control inside a Custom Control

I have a listbox inside a custom control. I use this custom control into a form. I would like to be able to get the listbox index changed event when I am working into the form. How can I do that?

If you are using WinForms, then you need to wire this event manually. Create event with the same signature on your custom control, create a handler for the even on the original listbox inside your custom control and in this handler fire the newly created event. (ignore all of this if you are using WPF)

You can add a proxy event to the custom control

public event EventHandler<WhatEverEventArgs> IndexChanged { 
    add { listBox.IndexChanged += value; }
    remove { listBox.IndexChanged -= value; } 
}

This can be a disadvantage of a UserControl. You have to re-publish the events and the properties of one or more of its embedded controls. Consider the alternative: if this UserControl only contains a ListBox then you are much better off simply inheriting from ListBox instead of UserControl.

Anyhoo, you'll need to re-fire the SelectedIndexChanged event. And surely you'll need to be able to let the client code read the currently selected item. Thus:

public partial class UserControl1 : UserControl {
    public event EventHandler SelectedIndexChanged;

    public UserControl1() {
        InitializeComponent();
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
        EventHandler handler = SelectedIndexChanged;
        if (handler != null) handler(this, e);
    }
    public object SelectedItem {
        get { return listBox1.SelectedItem; }
    }
}

Look into Ninjects Extension the MessageBroker, and on the index changed raise a published event, and subscribe to the event on the form side.

The messagebroker is rather useful in most cases.

Another thought would be implement an observer pattern and add the form as an observer to the controls event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM