Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionChanged sample

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.

like image 531
ns12345 Avatar asked Jan 03 '11 19:01

ns12345


2 Answers

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.

like image 131
Arxisos Avatar answered Sep 22 '22 20:09

Arxisos


 public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }
    private ObservableCollection<Person> persons = new ObservableCollection<Person>();


    public MainWindow()
    {
        InitializeComponent();
        dgPerson.ItemsSource = persons;
        persons.CollectionChanged += this.OnCollectionChanged;
    }


    void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        //Get the sender observable collection
        ObservableCollection<Person> obsSender = sender as ObservableCollection<Person>;
        NotifyCollectionChangedAction action = e.Action;
        if (action == NotifyCollectionChangedAction.Add)
            lblStatus.Content = "New person added";
        if (action == NotifyCollectionChangedAction.Remove)
            lblStatus.Content = "Person deleted";
    }
    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        Person p = new Person();
        p.FirstName = txtFname.Text;
        p.LastName = txtLname.Text;

        persons.Add(p);
    }

A very simple complete example here

like image 40
Alin Avatar answered Sep 22 '22 20:09

Alin