CommunityToolkit.Mvvm下ObservableCollection<接口>项变更视图不更新的解决方法
问题描述
根据相关文档,要让ObservableCollection中项的属性变更通知到视图,项必须实现INotifyPropertyChanged接口。使用CommunityToolkit.Mvvm时,通过特性可以无需样板代码实现该功能:
public class MyViewModel : ObservableObject { public ObservableCollection<MyItem> MyCollection { get; set; } //... } [INotifyPropertyChanged] // 无需样板代码 public partial class MyItem { public string MyProperty { get; set; } }
此时在MyViewModel中修改MyCollection里某一项的MyProperty,视图会自动更新。但当引入接口后,视图不再更新:
public class MyViewModel : ObservableObject { public ObservableCollection<IMyInterface> MyCollection { get; set; } //... } [INotifyPropertyChanged] public partial class MyItem : IMyInterface // MyProperty也在IMyInterface中定义 { public string MyProperty { get; set; } }
我已经尝试了两种方案:
- 让
IMyInterface继承INotifyPropertyChanged,但这需要在MyItem中显式实现PropertyChanged事件和OnPropertyMethod方法,而我正是为了避免样板代码才使用CommunityToolkit.Mvvm,因此不希望这么做; - 给
MyViewModel添加[INotifyPropertyChanged]特性,无任何效果;
是否存在我遗漏的无样板代码的解决方案?
目前我知道可以通过以下方式触发视图更新,但希望有更优的解决办法:
var item = MyCollection[0]; item.MyProperty = "new value"; MyCollection[0] = item;
内容的提问来源于stack exchange,提问作者Francesco B.
相关产品推荐
相关产品推荐

