绑定到Typeof的列表计数 [英] Bind to Count of List where Typeof

查看:59
本文介绍了绑定到Typeof的列表计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

这篇关于绑定到Typeof的列表计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆