在调用方法时捕获?

时间:2013-11-05 17:51:31

标签: .net vb.net winforms methods delegates

(首先很抱歉,因为我不知道如何正确地命名这个问题。)

当我从GUI中的Button调用它时,我需要执行某种操作:

Listview1.Items.Add(LVItem)

问题是我需要从其他类中执行此操作,我的意思是不继承ListView以引发自己的ItemIsAdded事件等...

那可能这样做吗?

我将展示一个更好地说明我的例子:

我有Form1课程:

Public Class Form1

Public WithEvents _undoManager As UndoManager

Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load

    _undoManager = New UndoManager(Listview1)

End Sub

Private Sub Button_AddItem_Click(sender As Object, e As EventArgs) _
Handles Button_AddItem.Click

    Listview1.Items.Add(LVItem)

End Sub

End Class

UndoManager班级:

Public Class UndoManager

    Delegate Sub AddDelegate(item As ListViewItem)

    Private Shared LV As ListView

    Private Shared ListView_Add_Method = New AddDelegate(AddressOf LV.Items.Add)

    Public Sub New(ByVal ListView As ListView)
        LV = ListView
    End Sub


    ' Here code to capture when the delegate method is called...

    private sub blahblahblah() handles ListView_Add_Method.IsCalled
      ' blah blah blah
    end sub    

End Class

然后当我在UndoManager类中调用Listview1.Items.Add(LVItem)来执行某种操作然后添加项目时,Form1类需要捕获(如果操作之前运行,则确实没有问题)或在调用Items.Add()方法后运行。

1 个答案:

答案 0 :(得分:1)

您已经有ItemAdded个事件 - 您缺少的是撤消管理器监视这些事件的方法。一种方法是只将一个汉德添加到一个将观察该事件的类中。例如,对于文本观察者:

Friend Overrides Function Watcher(ByVal ctl As Control) As Boolean

    ' can also be ComboBox, DateTimePicker etc
    If TypeOf Ctl is TextBox Then
          AddHandler ctl.Enter, AddressOf _Enter
          AddHandler ctl.Leave, AddressOf _Leave
            Return True

        Case Else
            Return False

    End Select

End Function

_enter获取BeforeText _leave将其与文本进行比较。如果有变化,则开始进行撤销。在您的情况下,您只需要监视ctl.ItemAdded和ctl.ItemRemoved来创建一个事件(无需比较)。只是有点聪明,您应该能够根据正在观看的事件轻松创建项目,标签和检查撤消操作。

观察者(其他UndoManager称之为Monitors)是创建撤消操作的人:

Private Sub _Leave(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim NewText As String = CType(sender, Control).Text

    If _Text <> NewText Then
        MyBase.OnNewAction(sender, _ 
           New AddActionArgs(UndoManager.UnDoReDo.UnDo, _
           New TextUndo(sender, _Text)))
    End If
End Sub