处理复合WinForms UserControl的某个组件上的Click事件

时间:2012-10-14 15:27:32

标签: c# winforms user-interface user-controls

我在C#中开发了一个WinForms UserControl UserControl本质上是一个复合控件,由几个子控件组成,例如:一个PictureBox,一个CheckBox,一个Label

从调用代码中,我希望能够为我的控件处理Click事件 但是,我希望当且仅当用户点击我的控件的某个组件时才会引发该事件,例如PictureBox。如果用户点击我控件中的任何其他位置,则不应该引发该事件。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

假设您使用的是WinForms。

您应该将来自pictureBox Click事件委托给您自己的事件,然后通过调用代码订阅它。

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();
    }
}