Piroks
Piroks

Reputation: 21

How to trigger onPropertyChanged event on ObservableCollection?

I have a custom class which inherits from ObservableCollection, where its Elemnent type raises OnPropertyChanged event but nothing happens

I have a following class

public class StudentsHandler: ObservableCollection<Student>{
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);
            Trace.WriteLine("OnCollectionChanged!");
        }

        protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            Trace.WriteLine("OnPropertyChanged!");
        }
}

And the Student class looks like this

public class Student : INotifyPropertyChanged
{
        public bool Present {
            get => _present;
            set
            {
                _present = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Present)));
                Trace.WriteLine("called!");
            }
        }
        private bool _present;

        public event PropertyChangedEventHandler PropertyChanged;
        ...
}

Changing the Present attribue of any student calls the setter, but StudentsHandler's event methods don't get called. How to do it correctly?

Upvotes: 0

Views: 238

Answers (1)

Isidoros Moulas
Isidoros Moulas

Reputation: 697

First of all ObservableCollection<Student> will take care for triggering any events in order the UI to be updated. If any item added or deleted from the list, then the change will be automatically displayed to the page (see Data binding and MVVM https://learn.microsoft.com/en-us/dotnet/maui/xaml/fundamentals/mvvm?view=net-maui-8.0)

Still, you have to slightly modify the model to inform the MVVM that a potential change to any of the properties of the specific item will trigger an event. For example, if something changes on item that is already loaded to your ObservableCollection the [ObservableProperty] annotation will trigger the event again and the UI will be refreshed instantly.

public partial class StudentModel :ObservableObject
{
    [Key]
    public int Id { get; set; }

    [ObservableProperty]
    string name;

}

The observable property is creating the below code. You can use this code to control what happens.


public string? Name
{
    get => name;
    set => SetProperty(ref name, value);
}

Hope that helps.

Upvotes: 0

Related Questions