0

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);
}
burnsi
  • 6,194
  • 13
  • 17
  • 27
leaf
  • 3
  • 2
  • 1
    subscribe to the `PropertyChanged` event of each `Person` object – Jason Feb 17 '23 at 12:45
  • You can also check this doc: [MVVM](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm#interactive-mvvm). It tells about `PropertyChanged`. – Jianwei Sun - MSFT Feb 22 '23 at 07:42

1 Answers1

0

You could do something like

foreach(var person in PersonList)
{
    person.PropertyChanged += yourPropertyChangedMethod;
}

That way you subscribe to every property changed event of the objects in your list.

EpicKip
  • 4,015
  • 1
  • 20
  • 37