6

请阅读这篇文章。我有与这篇文章中描述的相同的问题,但我试图在 VB.net 而不是 c# 中做。

我很确定要这样做,我必须使用自定义事件。(我使用了一个代码转换站点来了解自定义事件。)因此,当我在 IDE 中键入以下内容时:

公共自定义事件 AddRemoveAttendees As EventHandler

它扩展为以下代码片段。

Public Custom Event AddRemoveAttendees As EventHandler
    AddHandler(ByVal value As EventHandler)

    End AddHandler

    RemoveHandler(ByVal value As EventHandler)

    End RemoveHandler

    RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)

    End RaiseEvent
End Event

但我不知道该怎么办。直到今天,我从未听说过自定义事件。

我想要的底线是让按钮的单击事件冒泡到用户控件的容器。我知道我可以包装自己的事件,但我至少想在走得更远之前了解自定义事件。

赛斯

4

2 回答 2

8

要使用自定义事件来冒泡另一个控件的事件,您可以这样做:

Public Custom Event AddRemoveAttendees As EventHandler
    AddHandler(ByVal value As EventHandler)
        AddHandler _theButton.Click, value
    End AddHandler

    RemoveHandler(ByVal value As EventHandler)
        RemoveHandler _theButton.Click, value
    End RemoveHandler

    RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
        ' no need to do anything in here since you will actually '
        ' not raise this event; it only acts as a "placeholder" for the '
        ' buttons click event '
    End RaiseEvent
End Event

在其中AddHandlerRemoveHandler您只需传播调用以将给定的事件处理程序附加到/从控件的Click事件中删除。

为了扩展自定义事件的使用,这里是自定义事件的另一个示例实现:

Dim _handlers As New List(Of EventHandler)
Public Custom Event AddRemoveAttendees As EventHandler

    AddHandler(ByVal value As EventHandler)
        _handlers.Add(value)
    End AddHandler

    RemoveHandler(ByVal value As EventHandler)
        If _handlers.Contains(value) Then
            _handlers.Remove(value)
        End If
    End RemoveHandler

    RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
        For Each handler As EventHandler In _handlers
            Try
                handler.Invoke(sender, e)
            Catch ex As Exception
                Debug.WriteLine("Exception while invoking event handler: " & ex.ToString())
            End Try
        Next
    End RaiseEvent
End Event

现在,如上所示,除了常规的事件声明外,它几乎没有其他作用:

Public Event AddRemoveAttendees As EventHandler

它提供了一种类似的机制,允许附加和删除事件处理程序,以及引发事件。自定义事件添加的是额外级别的控制;您可以围绕事件的添加、删除和引发编写一些代码,在其中您可以执行规则,并稍微调整会发生的事情。例如,您可能希望限制附加到您的事件的事件处理程序的数量。为此,您可以更改AddHandler上面示例中的部分:

    AddHandler(ByVal value As EventHandler)
        If _handlers.Count < 8 Then
            _handlers.Add(value)
        End If
    End AddHandler

如果您不需要那种详细的控制,我认为没有必要声明自定义事件。

于 2009-07-03T21:26:43.097 回答
6

如果您想要与您提到的另一篇文章中相同的东西,这里是 VB.NET 等价物:

Public Custom Event AddRemoveAttendees As EventHandler

    AddHandler(ByVal value As EventHandler)
        AddHandler SaveButton.Click, value
    End AddHandler

    RemoveHandler(ByVal value As EventHandler)
        RemoveHandler SaveButton.Click, value
    End RemoveHandler

End Event

但我认为这不是一个好主意,因为sender事件的参数将是Button,而不是你的UserControl...

Instead, you could subscribe to the Button.Click event and raise you own event (with no explicit accessors)

于 2009-07-03T21:36:22.517 回答