Xamarin绑定ObservableCollection后CollectionView空白、ListView报错如何解决
问题根因排查
1. CollectionView空白原因
你的MyItems属性是普通自动属性,未实现属性变更通知,且实例化顺序错误:
- 代码先执行了
BindingContext = this,此时MyItems还是null - 后续为
MyItems赋值新的集合实例时,没有通知UI属性发生了变更,UI不会重新读取绑定值,因此没有内容展示。
2. ListView抛出类型转换错误原因
Xamarin.Forms的ListView的DataTemplate要求根元素必须是ViewCell类型,直接在DataTemplate下放置Label,运行时框架尝试将Label转换为ViewCell失败,因此抛出InvalidCastException。
修复方案
方案一:调整实例化顺序(临时修复)
把MyItems的实例化逻辑放在设置BindingContext之前,绑定时属性已经有有效值即可:
public ObservableCollection<string> MyItems { get; set; } public Home() { this.InitializeComponent(); // 先实例化集合 List<string> list = new List<string> { "One", "Two", "Three" }; this.MyItems = new ObservableCollection<string>(list); // 再设置BindingContext this.BindingContext = this; }
方案二:实现INotifyPropertyChanged(推荐,符合MVVM规范)
让页面实现INotifyPropertyChanged接口,属性变更时主动通知UI,后续如果需要动态修改MyItems的引用也能正常触发UI更新:
using System.ComponentModel; using System.Runtime.CompilerServices; public partial class Home : ContentPage, INotifyPropertyChanged { private ObservableCollection<string> _myItems; public ObservableCollection<string> MyItems { get => _myItems; set { _myItems = value; OnPropertyChanged(); } } public Home() { this.InitializeComponent(); this.BindingContext = this; List<string> list = new List<string> { "One", "Two", "Three" }; this.MyItems = new ObservableCollection<string>(list); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
ListView使用修复
如果要使用ListView,只需要在DataTemplate下加一层ViewCell包裹内容即可:
<ListView ItemsSource="{Binding MyItems}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label Text="{Binding .}" /> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
内容的提问来源于stack exchange,提问作者user1855026
相关产品推荐
相关产品推荐

