Is there an event that triggers if the number of ListViewItems in a ListView changes? (Windows Forms)

后端 未结 3 1591
一个人的身影
一个人的身影 2021-01-20 20:39

I\'d like to enable/disable some other controls based on how many items are in my ListView control. I can\'t find any event that would do this, either on the

相关标签:
3条回答
  • 2021-01-20 21:20

    I think the best thing that you can do here is to subclass ListView and provide the events that you want.

    0 讨论(0)
  • 2021-01-20 21:30

    I can't find any events that you could use. Perhaps you could subclass ListViewItemCollection, and raise your own event when something is added, with code similar to this.

    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
    
    0 讨论(0)
  • 2021-01-20 21:31

    @Domenic

    Not too sure, Never quite got that far in the thought process.

    Another solution might be to extend ListView, and when adding and removing stuff, instead of calling .items.add, and items.remove, you call your other functions. It would still be possible to add and remove without events being raised, but with a little code review to make sure .items.add and .items.remove weren't called directly, it could work out quite well. Here's a little example. I only showed 1 Add function, but there are 6 you would have to implement, if you wanted to have use of all the available add functions. There's also .AddRange, and .Clear that you might want to take a look at.

    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
    
    0 讨论(0)
提交回复
热议问题