Winforms – n event that triggers if the number of ListViewItems in a ListView changes? (Windows Forms)

eventslistviewwinforms

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 ListView itself or on the ListViewItemCollection. Maybe there's a way to generically watch any collection in C# for changes?

I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the ControlAdded and Layout events didn't work :(.

Best Solution

@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
Related Question