Reputation: 235
I'm using CommunityToolkit.Mvvm and having some issues with ObservableCollection. I've some view model declared like this:
public partial class LabourListViewModel: ObservableObject
{
[ObservableProperty]
private ObservableCollection<LabourJson> _labourList = [];
[RelayCommand]
public void LabourAdded( LabourJson labour )
{
LabourList.Insert( 0, labour );
}
}
Problem is that when method LabourAdded is called, UI doesn't update. I thought that ObservableProperty should observe changes and update UI accordingly?
If after insert I do like below then UI is updated, but why do I need to recreate list every time?
LabourList = new ObservableCollection<LabourJson>( LabourList.ToList() );
Upvotes: 0
Views: 76
Reputation: 26179
Your ObservableCollection
should be defined as follows:
ObservableCollection<LabourJson> LabourList { get; } = new ObservableCollection<LabourJson> LabourList
It is unnecessary to apply the [ObservableProperty]
attribute since your UI need not rely on the PropertyChanged
notification. Similarly, it is not recommended to provide a setter. The ObservableCollection
is initialized once by the initializer, and from this point onwards, it will broadcast CollectionChanged
events whenever you add, update, or delete from the collection.
Typically, consumers of such collections (e.g. ListView
and CollectionView
) are designed to listen for CollectionChanged
events to update their UI.
Upvotes: 2