我有一個 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));
}
uj5u.com熱心網友回復:
INotifyPropertyChanged是 UI 用來確定何時需要更新系結屬性的機制。如果您正在更改Pclass 上的屬性X,則X需要在修改時實作INotifyPropertyChanged并引發PropertyChanged事件P。
僅當ObservableCollection<T>從集合中洗掉或添加專案時才會引發事件。T當類上的個別屬性被修改時,它不會引發事件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490707.html
標籤:C# 安卓 asp.net 核心 xamarin 可观察的集合
