-1

我用 C# 开发了一个 WinForms UserControl。本质上是一个复合控件,由多个子控件组成,例如 a
、a 、 a等。UserControlPictureBoxCheckBoxLabel

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

我怎样才能做到这一点?

4

1 回答 1

1

假设您使用的是 WinForms。

您应该将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();
    }
}
于 2012-10-14T15:54:48.930 回答