MAUI中ListView无法显示/刷新ObservableCollection项的问题
问题分析与解决
你的ListView点击按钮后无法显示任何项,主要是以下几个核心问题导致的:
1. Variables是字段而非属性
数据绑定仅支持公共属性,但你当前的Variables是公共字段:
public ObservableCollection<Variable> Variables = new()
需修改为属性形式:
public ObservableCollection<Variable> Variables { get; set; } = new() { new Variable() { Name = "x", Value = 1 }, new Variable() { Name = "y", Value = 2 } };
2. BindingContext实例不一致
你在XAML中已经通过ContentPage.BindingContext创建了CalculatorViewModel实例,但在MainPage构造函数里又重新new了一个独立实例:
viewModel = new CalculatorViewModel();
这导致XAML绑定的ViewModel和按钮操作的ViewModel完全分离,你给后者添加数据,前者不会同步,ListView自然无内容。
解决:直接复用XAML中已创建的实例:
public MainPage() { InitializeComponent(); viewModel = (CalculatorViewModel)BindingContext; }
3. Entry的x:Name绑定错误
x:Name是编译时用于后台引用控件的名称,不能绑定数据,应改为绑定Text属性:
<Entry Text="{Binding Name}" Placeholder="name"/> <Entry Text="{Binding Value}" Placeholder="0" />
可选优化:实现属性变更通知
如果后续需要修改Variable属性并同步到UI,建议让Variable实现INotifyPropertyChanged接口:
using System.ComponentModel; using System.Runtime.CompilerServices; namespace Calc.Models { public class Variable : INotifyPropertyChanged { private string _name; private float _value; public string Name { get => _name; set => SetProperty(ref _name, value); } public float Value { get => _value; set => SetProperty(ref _value, value); } public event PropertyChangedEventHandler PropertyChanged; protected void SetProperty<T>(ref T backingStore, T value, [CallerMemberName] string propertyName = "") { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return; backingStore = value; OnPropertyChanged(propertyName); } protected void OnPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
完成以上修改后,ListView即可正常显示原有项和新添加的项。
内容的提问来源于stack exchange,提问作者Mariusz Szczerba
相关产品推荐
相关产品推荐

