首页 > 解决方案 > XAML 中的 ObservableCollection 项目数量

问题描述

如何在我使用 ObservableCollection 将商品选择到购物车中时绑定 ObservableCollection 商品数量。

    public ObservableCollection<ItemInCart> ItemsInCart
    {
        get { return _itemsInCart; }
        set { Set(ref _itemsInCart, value); }
    }
...
XAML:
cm:Message.Attach="[Event ItemClick] = [OnSellingItemSelected($clickedItem)]"

毕竟我正在收集这个集合并使用导航将它发送到下一页。尝试在 TextBlock 中显示收集量时遇到了更新数据的问题。

    public string ItemsInCartCount
    {
        get { return _itemsInCart.Count().ToString(); }
    }
...
XAML:
<TextBlock Text="{x:Bind ViewModel.ItemsInCartCount, Mode=OneWay}"

将新项目接收到 ItemsInCart 文本框中的数量没有变化。我怎样才能以正确的方式绑定?

标签: uwpuwp-xaml

解决方案


将新项目接收到 ItemsInCart 文本框中的数量没有变化。我怎样才能以正确的方式绑定?

ObservableCollectioncontains CollectionChanged,如果我们将新项目添加到 中ObservableCollection,将触发此事件。然后你可以重新加载 ItemsInCartCount

private void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
   ItemsInCartCount =  e.NewItems.Count.ToString();
}

请注意:ItemsInCartCount将通知值更改,因此我们需要对其onproperty进行更改。

private string _itemsInCartCount;
public string ItemsInCartCount
{
    get { return _itemsInCartCount; }
    set { Set(ref _itemsInCartCount, value); }
}

推荐阅读