如何在vb.net中创建可取消事件

时间:2009-08-28 04:14:51

标签: vb.net events event-handling

IN VB.NET(不是c#)......

我想创建一个可以被侦听器取消的事件。就像你可以取消winforms表格的结束事件一样,在这种情况下表格不会关闭。

我已经从EventArgs实现了一个派生类,它具有可设置的Cancel属性,如下所示:

Public Class AnnounceNavigateEventArgs
    Inherits EventArgs

    Private _cancel As Boolean = False

    ''' <summary>
    ''' Initializes a new instance of the AnnounceNavigateEventArgs class.
    ''' </summary>
    Public Sub New(ByRef cancel As Boolean)
        _cancel = cancel
    End Sub
    Public Property Cancel() As Boolean
        Get
            Return _cancel
        End Get
        Set(ByVal value As Boolean)
            _cancel = value
        End Set
    End Property

End Class

请注意,我将取消参数byRef传递给构造函数。

我设置的监听器将属性设置为Cancel = True。我认为ByRef意味着_cancel和cancel都指向堆栈上的相同位置,因此设置_cancel = true会使cancel = true。但这不是我得到的行为。 _cancel在setter中变为true但我猜构造函数的参数仍为false。

在vb.net中执行此操作的正确方法是什么?

赛斯

1 个答案:

答案 0 :(得分:8)

您可以在.NET框架中重用System.ComponentModel.CancelEventArgs类。

Public Event Announcing As EventHandler(Of AnnounceNavigateEventArgs)

Protected Sub OnAnnounce()
    Dim e As New AnnounceNavigateEventArgs

    RaiseEvent Announcing(Me, e)

    If Not e.Cancel Then
        ' announce
    End If
End Sub

Public Class AnnounceNavigateEventArgs
    Inherits System.ComponentModel.CancelEventArgs
End Class