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

主宰稳场 提交于 2019-11-30 22:49:24

问题


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.



来源:https://stackoverflow.com/questions/2242571/event-handler-that-will-be-called-when-an-item-is-added-in-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!