鼠标点击事件未触发

时间:2017-05-26 11:41:17

标签: c# winforms events

我创建了一个包含按钮的用户控件。目标是为我的按钮创建一个可以通过应用程序重用的自定义布局:

public partial class Button : UserControl
{
    public Button()
    {
        InitializeComponent();
        button1.BackColor = Color.FromArgb(0, 135, 190);
        button1.ForeColor = Color.Black;
    }

    [Description("Test text displayed in the textbox"), Category("Data")]
    public string TextSet
    {
        set { button1.Text = value; }
        get { return button1.Text; }
    }
}

当我将Button用户控件添加到我的应用程序并为MouseClick创建事件时,事件不会触发。 (显然,按钮的每个实例都有不同的鼠标点击事件)

我是否必须在我的按钮用户控制代码中执行某些操作才能转发鼠标单击事件?

1 个答案:

答案 0 :(得分:2)

您正在订阅用户控件的点击次数。但是,您正在单击位于用户控件上的按钮。因此,不会触发用户控件的单击事件。单击button1时,您可以手动引发用户控件的单击事件:

public partial class Button : UserControl
{
    public Button()
    {
        // note that you can use designer to set button1 look and subscribe to events
        InitializeComponent(); 
        button1.BackColor = Color.FromArgb(0, 135, 190);
        button1.ForeColor = Color.Black;
    }

    // don't forget to subscribe button event to this handler
    private void button1_MouseClick(object sender, MouseEventArgs e)
    {
        OnMouseClick(e); // raise control's event
    }

    // ...
}

但最好直接从Button班级继承你的按钮:

public partial class CustomButton : Button
{
    public CustomButton()
    {
        BackColor = Color.FromArgb(0, 135, 190);
        ForeColor = Color.Black;
    }

    [Description("Test text displayed in the textbox"), Category("Data")]
    public string TextSet
    {
        set { Text = value; }
        get { return Text; }
    }
}