是否有事件触发,如果ListView中的ListViewItems的数量发生变化? (Windows窗体)

时间:2020-03-05 18:48:36  来源:igfitidea点击:

我想根据我的ListView控件中有多少项来启用/禁用其他控件。我找不到任何可以做到这一点的事件,无论是在ListView本身还是ListViewItemCollection上。也许有一种方法可以通用地监视Cfor更改中的任何集合?

我也会对其他事件感到满意,即使某些事件有时在项目不变时也会触发,但例如ControlAddedLayout事件不起作用:(。

解决方案

回答

我找不到我们可以使用的任何事件。也许我们可以继承ListViewItemCollection,并在添加某些内容时使用类似于此的代码引发我们自己的事件。

Public Class MyListViewItemCollection
    Inherits ListView.ListViewItemCollection

    Public Event ItemAdded(ByVal Item As ListViewItem)

    Sub New(ByVal owner As ListView)
        MyBase.New(owner)
    End Sub

    Public Overrides Function Add(ByVal value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem
        Dim Item As ListViewItem

        Item = MyBase.Add(value)

        RaiseEvent ItemAdded(Item)

        Return Item
    End Function
End Class

回答

我认为我们可以在这里做的最好的事情是继承ListView并提供所需的事件。

回答

@Domenic

不太确定,在思考过程中从未做到那么远。

另一个解决方案可能是扩展ListView,并在添加和删除内容时调用其他函数,而不是调用.items.add和items.remove。仍然可以在不引发事件的情况下进行添加和删除,但是只需进行一点点代码审查即可确保未直接调用.items.add和.items.remove,效果很好。这是一个小例子。我只显示了1个Add函数,但是如果要使用所有可用的add函数,则必须实现6个。还有.AddRange和.Clear,我们可能想看看。

Public Class MonitoredListView
    Inherits ListView

    Public Event ItemAdded()
    Public Event ItemRemoved()

    Public Sub New()
        MyBase.New()
    End Sub

    Public Function AddItem(ByVal Text As String) As ListViewItem
        RaiseEvent ItemAdded()

        MyBase.Items.Add(Text)
    End Function

    Public Sub RemoveItem(ByVal Item As ListViewItem)
        RaiseEvent ItemRemoved()

        MyBase.Items.Remove(Item)
    End Sub

End Class