简体   繁体   中英

How can I create a custom event?

I have a custom set of UserControls: NavigationBar and NavigationItem.

I'd like that whenever the user clicks anywhere in the NavigationItem, an event is fired. I don't know how to set this up.

http://i.stack.imgur.com/ocP2D.jpg

I've tried this:

public partial class NavigationBar : UserControl
{
    public NavigationBar()
    {
        InitializeComponent();
        SetupEvents();
    }

    public List<NavigationItem> NavigationItems { private get; set; }
    public NavigationItem SelectedItem { get; set; }

    private void SetupEvents()
    {
        navigationItem1.Click += new EventHandler(navigationItemClick);
    }

    void navigationItemClick(object sender, EventArgs e)
    {
        MessageBox.Show("Clicked on " + sender.ToString());
    }
}

But that event only fires when the user specifically clicks on the NavigationItem control, but not when he clicks on the picture or text. (Those are PictureBox and Label).

What would be the best course of action? I'd like to create something well, not hacky code. Thanks!

Put something like this into your class:

public event EventHandler NavigationItemClick;

This creates a new event in your class named NavigationItemClick . The form designer will even see it.

In your method navigationItemClick you can do this to call the event.

EventHandler handler = this.NavigationItemClick;
if (handler != null)
{
    handler(this, EventArgs.Empty);
}

It is important to save the event into the handler variable to avoid race conditions. EventHandler is a delegate, so you call it like a method, hence the line in the if statement. The if itself makes sure that someone has attached to your 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