【问题标题】:Mouse click event not fireing鼠标点击事件未触发
【发布时间】:2017-05-26 11:41:16
【问题描述】:

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

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 创建一个事件时,该事件不会触发。 (显然每个按钮实例都会有不同的鼠标点击事件)

我是否必须在我的按钮用户控制代码中做一些事情来转发鼠标点击事件?

【问题讨论】:

  • 什么是button1?您设置事件处理程序的确切代码是什么?
  • 从代码中我看到 Button AS(inheritance) UserControl 但你说的是 UserControl Has(composition) Button??您还试图在哪里处理 UserControl 内或托管 UserControl 的表单内的点击事件?

标签: c# winforms events


【解决方案1】:

您正在订阅用户控制的点击。但是您正在单击位于用户控件上的按钮。因此不会触发用户控件的单击事件。当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; }
    }
}

【讨论】:

  • 我收到此错误:错误 CS0060 可访问性不一致:基类“按钮”比“自定义按钮”类更难访问
  • @Q-bertsuit 确保你继承自 System.Windows.Forms.Button 而不是你的 Button
  • 哦,等等,我遇到了另一个错误:错误 CS0115 'Button.Dispose(bool)': 找不到合适的方法来覆盖
  • @Q-bertsuit 这意味着您没有具有此类签名的虚拟方法 :) 您想在处置按钮时执行什么样的操作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
  • 2012-07-30
相关资源
最近更新 更多