【问题标题】:C# WinForms UserControl Mouse Event HelpC# WinForms UserControl 鼠标事件帮助
【发布时间】:2008-10-07 20:51:50
【问题描述】:

我有一个为我的项目创建的自定义控件。在此控件中,有几个子控件,例如 Label、PictureBox 和 LinkLabel。除了 LinkLabel,我希望当前在父控件上的鼠标悬停事件并让控件响应鼠标悬停。当您将鼠标悬停在控件上时,背景颜色会发生变化,但在子控件上时背景颜色不会发生变化;这是因为子控件上没有 MouseEnter 和 MouseLeave 事件。我通过将父控件委托方法添加到子控件来解决了这个问题。问题仍然存在,当我订阅父控件上的单击事件时,子控件上的单击事件也会被忽略。我可以订阅每个单独的子控件,但是如何强制父控件的单击事件?我通过搜索找到的术语是事件冒泡,但这似乎只适用于 ASP.NET 技术和框架。有什么建议吗?

【问题讨论】:

    标签: .net events controls


    【解决方案1】:

    您的描述使我相信您希望您的子控件和父控件都响应对子控件的单击。

    如果我正确理解您的问题,我建议订阅您的子控件的点击事件,并在这些事件处理程序中,调用一些常用方法以您希望的方式操纵父 UserControl 的状态(例如,更改背景颜色)。

    【讨论】:

      【解决方案2】:

      似乎其他人为我解决了这个问题。有朋友解释说C#控件支持一个叫InvokeOnClick(Control, EventArgs);的方法

      我为每个子控件添加了我的事件委托方法,对于单击事件,我为每个子控件创建了一个方法来使用。这反过来又调用 InvokeOnClick(this, new EventArgs());


      private void Control_Click(object sender, EventArgs e)
      {
          // this is the parent control.
          InvokeOnClick(this, new EventArgs());
      }
      
      private void IFLVControl_MouseEnter(object sender, EventArgs e)
      {
          this.BackColor = Color.DarkGray;
      }
      
      private void IFLVControl_MouseLeave(object sender, EventArgs e)
      {
          this.BackColor = Color.White;
      }
      

      【讨论】:

        【解决方案3】:

        我在处理所有子控件中的 Click 事件时遇到了类似的问题。代码是 VB.NET,但应该很容易调整。

        Public Shared Sub RelayEvents(ByVal usrcon As Windows.Forms.Control, ByVal del As System.EventHandler, Optional ByVal includeChildren As Boolean = True)
            For Each con As Windows.Forms.Control In usrcon.Controls
                AddHandler con.Click, del
                If includeChildren Then
                    RelayEvents(con, del)
                End If
            Next
        End Sub
        

        每当需要所需的级联时,可以将以下行添加到类的构造函数中。

        CustomMethods.RelayEvents(Me, New EventHandler(AddressOf Me_Click))
        

        【讨论】:

          【解决方案4】:

          CodeProject 的 Peter Rilling 提供了一些简单有效的代码,可以在 winforms(和 C#)中进行事件冒泡/广播。它真的很容易使用。

          http://www.codeproject.com/KB/cs/event_broadcast.aspx

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-04
            • 2016-02-06
            • 2013-11-11
            相关资源
            最近更新 更多