[英]How can I create a custom event?
I have a custom set of UserControls: NavigationBar and NavigationItem. 我有一个自定义的UserControls集:NavigationBar和NavigationItem。
I'd like that whenever the user clicks anywhere in the NavigationItem, an event is fired. 我希望每当用户单击NavigationItem中的任何位置时,都会触发一个事件。 I don't know how to set this up. 我不知道该如何设置。
http://i.stack.imgur.com/ocP2D.jpg 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. 但是,只有在用户专门单击NavigationItem控件时才会触发该事件,而在用户单击图片或文本时则不会触发。 (Those are PictureBox and Label). (这些是PictureBox和Label)。
What would be the best course of action? 最好的行动方针是什么? I'd like to create something well, not hacky code. 我想创建一些不错的东西,而不是hacky代码。 Thanks! 谢谢!
Put something like this into your class: 在您的班级中输入以下内容:
public event EventHandler NavigationItemClick;
This creates a new event in your class named NavigationItemClick
. 这将在您的名为NavigationItemClick
的类中创建一个新事件。 The form designer will even see it. 表单设计师甚至会看到它。
In your method navigationItemClick
you can do this to call the event. 在方法navigationItemClick
您可以执行此操作以调用事件。
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. 将事件保存到handler
变量中很重要,以避免出现竞争情况。 EventHandler
is a delegate, so you call it like a method, hence the line in the if
statement. EventHandler
是一个委托,因此您可以像调用方法一样调用它,因此if
语句中的行。 The if
itself makes sure that someone has attached to your event. if
本身可确保有人已加入您的活动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.