C # Get control events inside a user control

I have a list inside a custom control. I am using this custom form control. I would like to be able to receive the list index change event when I work on the form. How can i do this?

+3
source share
4 answers

This may be a disadvantage of UserControl. You must republish the events and properties of one or more of the built-in controls. Consider an alternative: if this UserControl contains only a ListBox, you are much better off just inheriting the ListBox instead of the UserControl.

Anyhoo, you need to restart the SelectedIndexChanged event. And, of course, you will need to allow the client to read the currently selected item. In this way:

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; }
    }
}
+3
source

If you use WinForms, you need to bind this event manually. Create an event with the same signature in your custom control, create an even handler in the source list inside the custom control, and in this handler, run the newly created event. (ignore all this if you are using WPF)

+4
source

-

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

Ninjects MessageBroker , .

Messagebroker .

- .

0

Source: https://habr.com/ru/post/1750523/


All Articles