0

I'm using CommunityToolkit.Mvvm in my .NET MAUI app's ViewModel's. One of the ObservableProperty's in my view model looks like this:

...
[ObservableProperty]
MyClassroomObject myClassroom;
...

And MyClassroomObject looks like this:

public class MyClassroomObject
{
   public Guid Id { get; set; }
   public string CourseName { get; set; }
   public List<Student> Students { get; set; } = new();
}

The Student class looks like this:

public class Student
{
   public Guid Id { get; set; }
   public Name { get; set; }
   public bool IsSelected { get; set; }
}

I bind the Students to a CollectionView and everything works fine. I then tap on a student's name to select the student and update some data which should trigger a change in the UI but it's not. Here's the method I call when I tap a student:

[RelayCommand]
void StudentSelected(Student selectedStudent)
{
   foreach(var item in MyClassRoom.Students)
      if(item.Id == selectedStudent.Id)
         item.IsSelected = true;
}

Shouldn't updating the IsSelected property value trigger a change in the UI? Currently, I'm not seeing any update in the UI. Any idea what maybe going on here?

Sam
  • 26,817
  • 58
  • 206
  • 383
  • Student isn’t Observable – Jason Mar 23 '23 at 23:15
  • I thought making the parent object observable made its children properties observable too. How would I make `Students` observable? Create another `[ObservableProperty]` for `Students`? – Sam Mar 23 '23 at 23:16
  • 1
    Observable isn’t inherited. That would be very expensive. Either make the student class inherit ObservableObject, or make the property you actually care about (IsSelected) an ObservableProperty – Jason Mar 23 '23 at 23:24

1 Answers1

1

As Jason suggested, if you want the UI update automatically once changing the property IsSelected of model Student, you need to inherit ObservableObject for class Student.

Please refer to the sample code below:

public class Student : ObservableObject 
{

     private bool isSelected;

     public bool IsSelected
     {
         get => isSelected;
            
         set =>SetProperty(ref isSelected, value);
     }

}

Alexandar May - MSFT
  • 6,536
  • 1
  • 8
  • 15