I have a model that implements PropertyChanged and in my ViewModel i have an ObservableCollection of this model. I want to know how can i call the method when a property of an object inside the Observablecollection changes.
In this sample code i want to call the OrderList method when i change the age property (or any property) of an item inside the PersonList.
Model
public class Person: NotifyBase
{
public string Name
{
get { return name; }
set { name = value; Notify(); }
}
public int Age
{
get { return age; }
set { age = value; Notify(); }
}
NotifyBase
public class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void Notificar([CallerMemberName] string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
VIewModel
public class PeopleViewModel : BaseViewModel
{
public ObservableCollection<Person> PersonList { get; set; } = new ObservableCollection<Person> {
new Person{ Name = "John", Age = 21},
new Person{ Name = "Mary", Age = 15},
new Person{ Name = "Steve", Age = 42},
new Person{ Name = "Marik", Age = 23},
};
}
void OrderList(){
List<Person> list = PersonList.OrderBy(x => x.Age).ToList();
PersonList.Clear();
foreach (var item in list )
PersonList.Add(item);
}