【发布时间】:2018-06-01 15:42:24
【问题描述】:
我是 Xamarin.Forms 的新手,我有一个带有项目源的列表视图。
ListView 的ItemSource 是ObserverableCollection
不幸的是,当我从ItemSource 中删除一个项目时,不会触发ItemDisapperaing 事件。是的,列表项已从 Android 设备的 UI 中删除。
但是我实现了ItemAppearing 并且效果很好!它触发了。
添加项目工作场景:
-
ShopCart.Instance.AddItem(randomItem)呼叫。 -
ShopItemListView.ItemsSource被新添加的项目刷新。 -
TotalAmount的文本更新了正确的数量。 因此调用了 ShopItem_NewItemAdded 函数!
从购物车场景中清除物品(不工作)
-
ShopCart.Instance.Clear()打来电话。 -
ShopItemListView.ItemShource将是空的!不在 UI 上的项目! - 但是
TotalAmount的文字没有变成0.0!它仍然具有以前的值。
似乎在 UI 元素上 TotalAmount 没有刷新!在调试中,我看到清除后ShopItemListView.ItemsSource 列表为空。
所以ShopItem_ItemRemoved函数没有被调用!
这里是 Xaml.cs
public ShopView()
{
InitializeComponent();
BindingContext = new ShopViewModel();
ShopItemListView.ItemsSource = Shop.Instance.ShopItems;
// This is triggered, it works
ShopItemListView.ItemAppearing += ShopItem_NewItemAdded;
// This event is not triggered, it does not work
ShopItemListView.ItemDisappearing += ShopItem_ItemRemoved;
}
// This event is not triggered, it does not work
private void ShopItem_ItemRemoved(object sender, ItemVisibilityEventArgs e)
{
// If I put a breakpoint here the debugger never comes into this method
TotalAmount.Text = Shop.Instance.ShopItems.Sum(si => si.Price).ToString();
if (Shop.Instance.ShopItems.Count == 0) {
ShopInformation.IsVisible = false;
}
}
// This is triggered, it works.
private void ShopItem_NewItemAdded(object sender, ItemVisibilityEventArgs e)
{
TotalAmount.Text = Shop.Instance.ShopItems.Sum(si => si.Price).ToString();
ShopInformation.IsVisible = true;
}
这是购物车单例实例
public sealed class ShopCart : INotifyPropertyChanged
{
private static readonly ShopCart _instance = new ShopCart();
private ShopCart()
{
ShopItems = new ObservableCollection<ShopCartItem>();
}
public static ShopCart Instance
{
get
{
return _instance;
}
}
public ObservableCollection<ShopCartItem> ShopItems { get; set; }
public void AddItem(ShopCartItem ShopCartItem)
{
ShopItems.Add(ShopCartItem);
OnPropertyChanged("ShopItems");
}
public void Clear()
{
ShopItems.Clear();
OnPropertyChanged("ShopItems");
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
ShopCart 实现了 INotifyPropertyChanged 接口。但似乎没有通知 UI 元素。
从购物车中删除所有商品后,如何刷新 UI 上的 TotalAmount 标签?
【问题讨论】:
-
你们互换名字有什么原因吗?
Shop.Instance.ShopItems和ShopCart.Instance.ShopItems -
另外,这一切都完成了吗
staticly?看起来购物车是您可以拥有多个实例的东西。
标签: xamarin xamarin.forms xamarin.ios xamarin.android