Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can someone point to an example where CollectionChanged is implemented. I am using wpf mvvm light. I tried to google, didn't find anything good enough.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

public ObservableCollection<string> Names { get; set; }

public ViewModel()
{
   names = new ObservableCollection<string>();
   Names.CollectionChanged += this.OnCollectionChanged;
}

void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   //Get the sender observable collection
   ObservableCollection<string> obsSender = sender as ObservableCollection<string>;

   List<string> editedOrRemovedItems = new List<string>();
   foreach(string newItem in e.NewItems)
   {
       editedOrRemovedItems.Add(newItem);
   }

   foreach(string oldItem in e.OldItems)
   {
       editedOrRemovedItems.Add(oldItem);
   }

   //Get the action which raised the collection changed event
   NotifyCollectionChangedAction action = e.Action;
}

For more information about the NotifyCollectionChangedEventArgs look here.

EDIT: Because you need a list of added/removed items, I modified the sample code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...