Bind to Count of List where Typeof

喜你入骨 提交于 2019-12-10 23:19:46

问题


I know how to Bind to Count, but how do I do it, if I only want the count where type is Product

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

I tried with a Property, But I am having problem keeping it in sync when Items are being added or removed.

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

回答1:


Additional to getting the correct number of items matching the type you have to guarantee that the PropertyChanged event of the view model is raised when the item collection is changed. So basically what you need is something like this:

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");
    }
}



回答2:


Using LINQ OfType() you can return value of following statement in ProductCount property getter:

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

BTW, to be more safe use following null-check condition:

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

BTW2, avoid using of the Cast<> in such cases because it throws the InvalidCastException exception in case of invalid cast operation.



来源:https://stackoverflow.com/questions/7686980/bind-to-count-of-list-where-typeof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!