You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 12:02:17