Reputation:
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.
https://i.sstatic.net/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!
Upvotes: 0
Views: 219
Reputation:
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.
Upvotes: 2