0

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

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

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)Form1Items.Add()

4

1 回答 1

1

you already have an ItemAdded event - what you are missing is a way for Undo Manager to watch for those events. One way is to just add a hander to a class which will watch for that event. For instance, for text watcher:

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 gets the BeforeText _leave compares it to the text now. if there is a change, then begin to make an undoaction. In your case, you only need to monitor ctl.ItemAdded and ctl.ItemRemoved to make an event (no need to compare). Being only a little clever you should be able to easily create Item, Label and Check Undo actions based on the event being watched.

The watchers (that other UndoManager called them Monitors) is the one that creates undo actions:

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
于 2013-11-05T18:28:56.207 回答