【问题标题】:Bind to Count of List where Typeof绑定到 Typeof 的列表计数
【发布时间】:2011-12-02 23:20:06
【问题描述】:

我知道如何绑定到计数,但是如果我只想要类型为 Product 的计数,我该怎么做

<TextBlock Text="{Binding Items.Count}" />
Items = new ObservableCollection<object>();

我尝试使用属性,但在添加或删除项目时无法保持同步。

    public int ProductCount
            {
                get
                {
                    return Items.Cast<object>().Count(item => item.GetType() == typeof (ProductViewModel));
                }
            }

【问题讨论】:

  • 您是否尝试过使用 LINQ TypeOf 扩展方法?

标签: c# wpf binding inotifypropertychanged


【解决方案1】:

使用 LINQ OfType() 您可以在 ProductCount 属性获取器中返回以下语句的值:

return Items.OfType<ProductViewModel>().Count();

顺便说一句,为了更安全地使用以下空检查条件:

return Items == null ? 0 : Items.OfType<ProductViewModel>().Count();

顺便说一句,在这种情况下避免使用Cast<>,因为它会在强制转换操作无效的情况下引发InvalidCastException 异常。

【讨论】:

  • 不得不接受另一个答案,因为它更完整,但非常感谢您的回答,非常有帮助。
【解决方案2】:

除了获得与类型匹配的正确数量的项目外,您还必须保证在项目集合更改时引发视图模型的PropertyChanged 事件。所以基本上你需要的是这样的:

class ProductViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private ObservableCollection<object> m_Items;
    public ObservableCollection<object> Items
    {
        get { return m_Items; }
        set 
        { 
            if(m_Items != null)
                m_Items.CollectionChanged -= HandleItemsCollectionChanged;

            m_Items = value; 
            m_Items.CollectionChanged += HandleItemsCollectionChanged; 

            PropertyChanged(this, new PropertyChangedEventArgs("Items");
        }
    }

    public int ProductCount
    {
        get
        {
            return Items == null 
                ? 0 
                : Items.OfType<ProductViewModel>().Count();
        }
    }

    private void HandleItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        PropertyChanged(this, new PropertyChangedEventArgs("ProductCount");
    }
}

【讨论】:

  • 在 Items.Set 方法中,如果 m_Items 不为空,我将取消注册以前的事件处理程序。
猜你喜欢
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 2016-10-25
  • 1970-01-01
  • 2010-10-10
相关资源
最近更新 更多