加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何为vb.net winforms用户控件公开和引发自定义事件

发布时间:2020-12-17 00:07:55 所属栏目:大数据 来源:网络整理
导读:请阅读 THIS帖子.我有同样的问题,如本文所述,但我试图在VB.net而不是c#. 我很确定这样做我必须使用自定义事件. (我使用code conversion site来了解自定义事件.)所以在IDE中键入以下内容时: 公共自定义事件AddRemoveAttendees As EventHandler 它扩展为以下
请阅读 THIS帖子.我有同样的问题,如本文所述,但我试图在VB.net而不是c#.

我很确定这样做我必须使用自定义事件. (我使用code conversion site来了解自定义事件.)所以在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

但我无法弄清楚如何处理它.直到今天,我从未听说过自定义事件.

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

赛斯

要使用自定义事件来冒泡另一个控件的事件,您可以这样做:
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

在AddHandler和RemoveHandler中,您只需传播调用以将给定的事件处理程序附加到控件的Click事件或从控件的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

它提供了一种类似的机制,允许附加和删除事件处理程序,以及引发事件. Custom事件添加的内容是额外的控制级别;你可以围绕添加,删除和引发事件编写一些代码,在这些代码中你可以强制执行规则,并调整会发生什么.例如,您可能希望限制附加到事件的事件处理程序的数量.要实现这一点,您可以更改上面示例中的AddHandler部分:

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

如果您不需要这种详细控件,我认为无需声明自定义事件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读