MAUI中CollectionView绑定数据需使用ObservableCollection作为数据源、设置BindingContext指向ViewModel、并在XAML中通过ItemsSource="{Binding Items}"和ItemTemplate内Binding路径正确关联属性。
MAUI 中给 CollectionView 绑定数据,核心是通过 绑定上下文(BindingContext) + 数据模板(DataTemplate) 实现。只要数据源是可观察集合(如 ObservableCollection),且控件设置了正确的绑定路径,列表就能自动刷新。
在页面的后台代码或 XAML 中,把包含列表数据的 ViewModel 赋给页面的 BindingContext:
this.BindingContext = new MyViewModel();
ObservableCollection 类型的属性(比如叫 Items),确保它支持通知变化List 或数组——它们不会触发 UI 更新在 XAML 中声明 CollectionView,用 ItemsSource 绑定到 ViewModel 的集合属性:
Items 是 public 属性,且命名与 BindingContext 中的字段/属性名完全一致仅绑定数据源还不够,得告诉 MAUI 每一项长什么样:
CollectionView 内添加 ItemTemplate,里面用 DataTemplate 包裹布局Binding 的路径(如 Title)要和数据项(ItemModel)中的 public 属性名一致因为用了 ObservableCollection,直接操作集合即可实时反映到界面:
Items.Add(new ItemModel { Title = "新条目" });
Items.Clear();
Clear() + AddRange() 或封装为属性 setter 并调用 OnPropertyChanged)ItemModel 实现了 INotifyP
ropertyChanged
基本上就这些。关键点就三个:用对集合类型、设好 BindingContext、写对 Binding 路径。不复杂但容易忽略细节。