3

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

4

4 回答 4

2

Your description leads me to believe that you want both your child and your parent controls to respond to a click on the child control.

If I understand your question correctly, I'd suggest subscribing to your child controls' click events and, in those event handlers, calling some common method that manipulates the state of the parent UserControl in the manner that you desire (e.g., changing the background color).

于 2008-10-07T20:56:42.203 回答
1

It seems that someone else solved it for me. A friend explained that C# controls support a method called InvokeOnClick(Control, EventArgs);

I added my event delegate methods to each child control, and for the click event, I created a single method for each child control to use. This in turn calls 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;
}
于 2008-10-07T21:22:00.280 回答
1

我在处理所有子控件中的 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))
于 2010-11-09T12:11:55.210 回答
0

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

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

于 2008-11-25T20:15:12.003 回答