JL.
JL.

Reputation: 81342

Custom event in a user control

My user control has a private binding source:

private System.Windows.Forms.BindingSource _bsMyBindingSource;

The binding source object supports the List changed event, which is exactly the event I want to catch and use.

private void _bsMyBindingSource_ListChanged(object sender, ListChangedEventArgs e)
      {

      }

Now... since _bsMyBindingSource is a private member I don't want to expose this event directly (if that is even possible?).

I want my user control to have a OnChange event, which will be invoked when the internal _bsMyBindingSource_ListChanged is invoked.

How can this be done?

Upvotes: 0

Views: 1986

Answers (1)

Rhumborl
Rhumborl

Reputation: 16609

You just need to raise your custom event from the _bsMyBindingSource_ListChanged handler.

You can keep it as a ListChangedEventHandler:

public class MyUserControl : UserControl
{
    public event ListChangedEventHandler OnChange;

    private void _bsMyBindingSource_ListChanged(object sender, ListChangedEventArgs e)
    {
        // if no listeners, OnChange will be null, so need to check
        if(this.OnChange != null)
        {
            this.OnChange(this, e);
        }
    }
}

Or do a custom event type:

public class MyUserControl : UserControl
{
    public event EventHandler OnChange;

    private void _bsMyBindingSource_ListChanged(object sender, ListChangedEventArgs e)
    {
        // if no listeners, OnChange will be null, so need to check
        if(this.OnChange != null)
        {
            this.OnChange(this, new EventArgs());
        }
    }
}

Then your page or whatever can listen to this event:

public class MyPage : Page
{
    private MyUserControl myControl;

    public void MyPage_Load()
    {
        myControl.OnChange += myControl_OnChange;
    }

    private void myControl_OnChange(object sender, ListChangedEventArgs e)
    {
        // ... do something
    }
}

Upvotes: 2

Related Questions