I went through SO questions on this topic and thought I followed the examples carefully but I still don't see a UI update when a property of an item in a CollectionView
gets updated.
First, I made sure the property in my model is decorated with ObservableProperty
:
public partial class Student : ObservableObject
{
public int Id { get; set; }
public string Name { get; set; }
[ObservableProperty]
bool isRegistered;
}
I then use an ObservableCollection
in my view model which is also decorated with ObservableProperty
:
public partial class MyViewModel : ObservableObject
{
public MyViewModel()
{
var student = new Student
{
Id = 123,
Name = "John Doe",
IsRegistered = false
};
Students.Add(student);
student = new Student
{
Id = 234,
Name = "Jane Doe",
IsRegistered = false
};
Students.Add(student);
}
[ObservableProperty]
ObservableCollection<Student> students = new();
[RelayCommand]
void UpdateRegistrations()
{
foreach(var item in Students)
item.IsRegistered = true;
}
}
Here's the XAML:
<ContentPage...>
<Grid
RowDefinitions="*,50">
<CollectionView
Grid.Row="0"
ItemsSource="{Binding Students}">
<CollectionView.ItemTemplate>
<DataTemplate
x:DataType="model:Student">
<Grid
ColumnDefinitions="*,30">
<Label
Grid.Column="0"
Text="{Binding Name}" />
<Image
Grid.Column="1"
Source="checkmark.png"
IsVisible="{Binding IsRegistered}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Button
Grid.Row="1"
Text="Update Data"
Command="{Binding UpdateRegistrationsCommand}" />
</Grid>
</ContentPage>
I don't see the change in IsRegistered
reflected in the UI after executing UpdateRegistrations()
. What am I missing here? I'm under the impression that CommunityToolkit.Mvvm handles INotifyPropertyChanged
logic. Do I need to handle the change manually?