[英]Xamarin - Update Observable Collection Not Working
我有一个 Xamarin 项目,其中有一个购物车页面。 每当我单击添加或删除按钮时,我都会尝试更新数据,但事实并非如此。 这是代码
public class CartViewModel : BindableObject
{
....
private ObservableCollection<OrderDisplay> _ordersList;
public ObservableCollection<OrderDisplay> OrdersList
{
get => _ordersList;
set
{
_ordersList = value;
OnPropertyChanged();
}
}
然后我有AddTotal
我尝试更新它。 按下添加或删除按钮时调用
private async void AddTotal(OrderDisplay oCart, int quantity)
{
decimal total = 0;
int index = 0;
if (oCart != null)
{
foreach (OrderDisplay obj in OrdersList)
{
if (obj.Id == oCart.Id)
{
break;
}
index += 1;
}
OrdersList[index].Quantity = quantity;
OrdersList[index].Total = quantity * OrdersList[index].Price;
//OrdersList = null;
//OrdersList = tempOrdersList;
var order = await _apiService.GetOrderById(OrdersList[index].Id, token);
order.Data.Quantity = OrdersList[index].Quantity;
var orderUpdated = await _apiService.UpdateOrder(Convert.ToString(order.Data.Id), token, order.Data);
if (!orderUpdated)
{
await _messageService.ShowMessageAsync("Error", "Ha ocurrido un error.", "Ok", "");
return;
}
}
foreach (OrderDisplay order in OrdersList)
{
total = order.Total + total;
}
LblTotalCart = string.Format("{0:N2}€", total);
}
对于上下文,这里是视图
我不知道该怎么做。 请帮忙。
编辑
我尝试用INotifyPropertyChanged
来做,但给了我NullReference
。 我不知道这是否正确
public class OrderDisplay : INotifyPropertyChanged
{
//public int Id { get; set; }
//public int Quantity { get; set; }
//public decimal Price { get; set; }
//public decimal Total { get; set; }
//public CrProduct Product { get; set; }
private int id;
public int Id
{
get { return id; }
set
{
id = value;
OnPropertyChanged("Id");
}
}
public int quantity;
public int Quantity
{
get { return quantity; }
set
{
quantity = value;
OnPropertyChanged("Quantity");
}
}
public decimal price;
public decimal Price
{
get { return price; }
set
{
price = value;
OnPropertyChanged("Price");
}
}
public decimal total;
public decimal Total
{
get { return total; }
set
{
total = value;
OnPropertyChanged("Total");
}
}
public CrProduct product;
public CrProduct Product
{
get { return product; }
set
{
product = value;
OnPropertyChanged("Product");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
INotifyPropertyChanged
是 UI 用来确定何时需要更新绑定属性的机制。 如果要更改类X
的属性P
,则X
需要实现INotifyPropertyChanged
并在修改P
时引发PropertyChanged
事件。
ObservableCollection<T>
仅在从集合中删除或添加项目时引发事件。 当类T
上的单个属性被修改时,它不会引发事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.