As written everywhere (e.g. here, here, here, here...), reporting an ObservableCollection
item property change to a view requires the item to implement INotifyPropertyChanged
.
Using CommunityToolkit.Mvvm this can be done using an attribute:
public class MyViewModel : ObservableObject
{
public ObservableCollection<MyItem> MyCollection { get; set; }
//...
}
[INotifyPropertyChanged] // yay! No boilerplate code needed
public partial class MyItem
{
public string MyProperty { get; set; }
}
If somewhere inside MyViewModel
there is a change to the MyProperty
of an item of MyCollection
, the view will be updated.
What if an interface comes into play?
public class MyViewModel : ObservableObject
{
public ObservableCollection<IMyInterface> MyCollection { get; set; }
//...
}
[INotifyPropertyChanged]
public partial class MyItem : IMyInterface // MyProperty is in IMyInterface too
{
public string MyProperty { get; set; }
}
The view seems not to be updated anymore. I tried:
- Inheriting
INotifyPropertyChanged
inIMyInterface
(that requires explicit implementation of thePropertyChanged
event andOnPropertyMethod
method inMyItem
, which I don't want as otherwise I would have not used CommunityToolkit.Mvvm) - Adding
[INotifyPropertyChanged]
toMyViewModel
(expecting nothing but there was an answer somewhere telling that)
Is there an obvious, no-boilerplate solution that I'm missing here?
The view is updated if I do something like suggested here
var item = MyCollection[0];
item.MyProperty = "new value";
MyCollection[0] = item;
but I hope there's a better way.