Event handler that will be called when an item is

2019-04-21 07:09发布

问题:

Is there an event handler that will be called when an item is added in a listbox in WPF?

Thanks!

回答1:

The problem is that the INotifyCollectionChanged interface which contains the event handler is explicitly implemented, which means you have to first cast the ItemCollection before the event handler can be used:

public MyWindow()   
{   
    InitializeComponent();   

    ((INotifyCollectionChanged)mListBox.Items).CollectionChanged +=   
        mListBox_CollectionChanged;   
}   

private void mListBox_CollectionChanged(object sender,    
    NotifyCollectionChangedEventArgs e)   
{   
    if (e.Action == NotifyCollectionChangedAction.Add)   
    {   
        // scroll the new item into view   
        mListBox.ScrollIntoView(e.NewItems[0]);   
    }       
}

Ref.

Josh's advice about the observable collection should also be considered.



回答2:

Take a different approach. Create an ObservableCollection (which does have such an event) and set the ItemsSource of the ListBox to this collection. In other words, in WPF you should think about the problem differently. The control isn't necessarily what is being modified ... the collection behind it is.

UPDATE
Based on your comment to Mitch's answer which indicates your binding source is actually an XML document, I suggest looking into hooking up to the XObject.Changed event of the XML document/element/etc. This will give you change information about the XML structure itself - not the ItemCollection which is an implementation detail you shouldn't need to consider. For example, ItemCollection (or any INotifyCollectionChanged) doesn't guarantee an individual event for every change. As you noted, sometimes you'll just get a generic reset notification.