21

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.

2
  • In the comments of answer to the question you post you will find "Modified my code above to make it more clear. Also this should work with any ItemsControl (ListBox or ListView)." - What problem are you having in particular?
    – Slugart
    Jun 4, 2012 at 15:42
  • @Slugart Thank you for your reply, the problem I having is that the method BeginInvoke does not accept the declaration as the example. It says that DispatcherPriority does not exist
    – Dante
    Jun 4, 2012 at 15:47

2 Answers 2

65

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.

3
  • 1
    This does not work for me. I get Unable to cast object of type 'ListViewItemCollection' to type 'System.Collections.Specialized.INotifyCollectionChanged'.
    – Arvo Bowen
    Oct 26, 2013 at 4:51
  • 1
    For anyone else who is curious, ListView.Items is of type ItemsCollection. This inherits from CollectionView which implements INotifyCollectionChanged. Looking at MSDN, this was true for .NET 3.0 - 4.6. @Arvo ListViewItemCollection only implements IList, ICollection, IEnumerable and doesn't inherit from anything, hence your exception.
    – DJH
    May 6, 2015 at 11:24
  • Works with WPF Listbox too. If a observablecollection<string> is bound, the the first occurrence will be brought into View! So if the same value can occur multiple times, use a class with one property to bind (observablecollection<myclass>) and set the DisplayMemberPath accordingly.
    – dba
    Nov 5, 2017 at 15:26
-2

Note: This solution was meant for a WinForms ListView.

In my case I ended up coming to a fork in the road with 2 choices...

(1) Create a custom ListView control that inherits a ListView's class. Then add a new event to be raised when any item is added, deleted, or ListView is cleared. This path seemed really messy and long. Not to mention the other big issue that I would need to replace all my original ListViews with the newly created Custom ListView control. So I passed on this!


(2) With every add, delete, or clear call to the listview I also called another function simulating the CollectionChanged event.

Create the new event like function...

private void myListViewControl_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    //The projects ListView has been changed
    switch (e.Action)
    {
        case NotifyCollectionChangedAction.Add:
            MessageBox.Show("An Item Has Been Added To The ListView!");
            break;
        case NotifyCollectionChangedAction.Reset:
            MessageBox.Show("The ListView Has Been Cleared!");
            break;
    }
}

Add an item to the ListView elsewhere...

ListViewItem lvi = new ListViewItem("ListViewItem 1");
lvi.SubItems.Add("My Subitem 1");
myListViewControl.Items.Add(lvi);
myListViewControl_CollectionChanged(myListViewControl, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, lvi, lvi.Index));

Clear the ListView elsewhere...

myListViewControl.Items.Clear();
myListViewControl_CollectionChanged(myListViewControl, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
6
  • It's pretty odd that Dante's solution doesn't work for you, especially when your work-around involves... INotifyCollectionChanged. ((INotifyCollectionChanged)MyList.Items).CollectionChanged += MyListChanged worked for me. Are you sure you put the parenthesis in the right places? Oct 31, 2013 at 19:45
  • Maybe it has something to do with WPF, I don't use that, I'm using WinForms. Not sure, all I know is that all namespaces are accounted for and all references work perfect with those objects/types. I don't even really get how you could cast a collection of listView.Items to INotifyCollectionChanged (Not saying it can't be done, I just don't get it). Everything else looks good except that part. I'm more then willing to try something out if you tell me. But as it stands my VS 2010 says no! ;)
    – Arvo Bowen
    Oct 31, 2013 at 19:52
  • 2
    WinForms and WPF are two totally different beasts; a WinForms ListView has nothing to do with a WPF ListView! The WPF ListViewItemCollection implements INotifyCollectionChanged; this allows WPF's powerful data binding capabilities to detect changes in the list and [almost] automagically keep everything up-to-date. You should consider leaving WinForms behind and trying out WPF - once you get the hang of it, you'll never look back! :) Oct 31, 2013 at 20:25
  • 1
    Thanks! Noted. I edited Dante's answer for a few reasons (adding a note at the top for pure c# developers such as me). As soon as the edit is accepted it gets a vote up from me. I'll try WPF soon! ;) I need to move from 2010 to 2013 too. hehe
    – Arvo Bowen
    Oct 31, 2013 at 20:34
  • 1
    No problem, except the question is already tagged wpf... (not my downvote) Oct 31, 2013 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.