Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Raise an Event when Item is added in ListView

Tags:

I am working on WPF and I am using a ListView, and I need to fire an event when an item is added to it. I have tried this:

var dependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(ListView));         if (dependencyPropertyDescriptor != null)         {                dependencyPropertyDescriptor.AddValueChanged(this, ItemsSourcePropertyChangedCallback);         } 

.....

 private void ItemsSourcePropertyChangedCallback(object sender, EventArgs e)     {          RaiseItemsSourcePropertyChangedEvent();     } 

But It seems to be working only when the entire collection is changed, I have read this post: event-fired-when-item-is-added-to-listview, but the best answer applies for a listBox only. I tried to change the code to ListView but I wasnt able to do that.

I hope You can help me. Thank you in advance.

like image 923
Dante Avatar asked Jun 04 '12 15:06

Dante


1 Answers

Note this only works for a WPF Listview!

After some research I have found the answer to my question and It's really easy:

public MyControl() {     InitializeComponent();     ((INotifyCollectionChanged)listView.Items).CollectionChanged +=  ListView_CollectionChanged; }  private void ListView_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)      {     if (e.Action == NotifyCollectionChangedAction.Add)     {       // scroll the new item into view          listView.ScrollIntoView(e.NewItems[0]);     } } 

Actually, the NotifyCollectionChangedAction enum allows your program to inform you about any change such as: Add, Move, Replace, Remove and Reset.

like image 199
Dante Avatar answered Oct 17 '22 22:10

Dante