C# 处理复合WinForms UserControl的特定组件上的单击事件
我用C#开发了一个WinFormsC# 处理复合WinForms UserControl的特定组件上的单击事件,c#,winforms,user-interface,user-controls,C#,Winforms,User Interface,User Controls,我用C#开发了一个WinFormsUserControl。 UserControl本质上是一个由多个子控件组成的复合控件,例如PictureBox、复选框、标签等 从调用代码中,我希望能够处理控件的单击事件。 但是,当且仅当用户单击我控件的某个组件(例如PictureBox)时,我希望引发该事件。如果用户单击我控制范围内的任何其他位置,则不应引发该事件 我该怎么做呢?假设您使用的是WinForms 您应该将pictureBox中的单击事件委派到您自己的事件中,然后从调用代码订阅该事件 publi
UserControl
。UserControl
本质上是一个由多个子控件组成的复合控件,例如PictureBox
、复选框
、标签等
从调用代码中,我希望能够处理控件的单击事件。
但是,当且仅当用户单击我控件的某个组件(例如PictureBox
)时,我希望引发该事件。如果用户单击我控制范围内的任何其他位置,则不应引发该事件
我该怎么做呢?假设您使用的是WinForms
您应该将pictureBox中的单击事件委派到您自己的事件中,然后从调用代码订阅该事件
public class MyControl : System.Windows.Forms.UserControl
{
// Don't forget to define myPicture here
////////////////////////////////////////
// Declare delegate for picture clicked.
public delegate void PictureClickedHandler();
// Declare the event, which is associated with the delegate
[Category("Action")]
[Description("Fires when the Picture is clicked.")]
public event PictureClickedHandler PictureClicked;
// Add a protected method called OnPictureClicked().
// You may use this in child classes instead of adding
// event handlers.
protected virtual void OnPictureClicked()
{
// If an event has no subscribers registerd, it will
// evaluate to null. The test checks that the value is not
// null, ensuring that there are subsribers before
// calling the event itself.
if (PictureClicked != null)
{
PictureClicked(); // Notify Subscribers
}
}
// Handler for Picture Click.
private void myPicture_Click(object sender, System.EventArgs e)
{
OnPictureClicked();
}
}