Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handler that will be called when an item is added in a listbox

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

Thanks!

like image 393
lionheart Avatar asked Feb 11 '10 05:02

lionheart


2 Answers

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.

like image 137
Mitch Wheat Avatar answered Oct 18 '22 12:10

Mitch Wheat


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.

like image 31
Josh Avatar answered Oct 18 '22 12:10

Josh