事件处理抽象类

时间:2010-07-06 18:46:15

标签: vb.net events raiseevent

基本上,我有一个自定义子表单类,其中包含将传递给父表的事件。在自定义子窗体中,我有一个继承DevExpress用户控件类的“MustInherit”类的声明。

原因是我有很多来自这个基类的用户控件,而子表单可以有这些控件中的任何一个的实例,并不关心哪个。唯一的要求是子表单可以以相同的方式处理来自每种控件的相同事件。

有些人对代码片段进行了淡化(不幸的是很长时间):

'''Inherited Class
Public Class ChildControlInheritedClass
    'A Button Click event that starts the chain of events.
    Private Sub btnMoveDocker_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvertToTab.Click
        OnMoveToDocker(Me, New ChildGridMoveArgs(Me))
    End Sub
End Class

'''Base Class
Public MustInherit Class ChildControlBaseClass
    Inherits DevExpress.XtraEditors.XtraUserControl
    Public Class ChildGridMoveArgs
        Inherits System.EventArgs
        Public Sub New(ByVal _ChildControl As ChildControlInheritedClass)
            ChildControl = _ChildControl
        End Sub
        Public ChildControl As ChildControlInheritedClass
    End Class
    Public Event MoveToDocker(ByVal sender As Object, ByVal e As ChildGridMoveArgs)
    Protected Overridable Sub OnMoveToDocker(ByVal sender As Object, ByVal e As ChildGridMoveArgs)
        '''Once this RaiseEvent is fired, nothing happens. The child form is oblivious.
        RaiseEvent MoveToDocker(sender, e)
    End Sub
End Class

'''Child Form Class
Public Class ChildForm
    Private WithEvents cgChild As ChildControlBaseClass
    Public Property ChildGrid() As ChildControlInheritedClass
        Get
            Return cgChild
        End Get
        Set(ByVal value As ChildControlInheritedClass)
            RemoveHandler cgChild.MoveToDocker, AddressOf cgChild_MoveToDocker
            cgChild.Dispose()
            cgChild = Nothing
            cgChild = value
            AddHandler cgChild.MoveToDocker, AddressOf cgChild_MoveToDocker
        End Set
    End Property
    Public Event MoveToDocker(ByVal sender As Object, ByVal e As ChildControlInheritedClass.ChildGridMoveArgs)
    Public Sub cgChild_MoveToDocker(ByVal sender As Object, ByVal e As ChildControlInheritedClass.ChildGridMoveArgs)
        RaiseEvent MoveToDocker(sender, New ChildControlInheritedClass.ChildGridMoveArgs(cgChild))
    End Sub
End Class

Public Class frmMain
    Private Sub OpenNewWindow()
        Dim frm As New ChildForm
        Dim chld As New ChildControlInheritedClass
        frm.ChildGrid = chld
        frm.Show()
    End Sub
End Class

简而言之,这就是我如何制作儿童形式以及如何设定一切。但是当我按下继承的子控件中的按钮时,事件只会到达基类,并且永远不会将RaiseEvent遍历到假设处理事件的子窗体中。

我甚至在这里的球场吗?

感谢阅读!

1 个答案:

答案 0 :(得分:0)

您忘记使用AddHandler或Handles标识符添加事件句柄。请参阅下面的Handles cgChild.MoveToDocker标识符。


Public Class ChildForm
    ...
    Public Sub cgChild_MoveToDocker(ByVal sender As Object, ByVal e As ChildControlInheritedClass.ChildGridMoveArgs) Handles cgChild.MoveToDocker
        RaiseEvent MoveToDocker(sender, New ChildControlInheritedClass.ChildGridMoveArgs(cgChild))
    End Sub
End Class