在WinRT中,实现INotifyCollectionChanged而不是更新ItemsControl的Collection

时间:2013-01-29 16:51:44

标签: windows-8 itemssource inotifycollectionchanged

我正在编写自己的集合类,它也实现了INotifyCollectionChanged。我在Windows 8商店应用程序(winRT)中使用它。我编写了一个单元测试,证明修改列表的内容会引发所有正确的事件,而“正常”的可观察集合会引发相同的事件。但是,当我将ItemsControl的ItemsSource属性(我尝试使用GridView,ListView,甚至普通的ItemsControl)绑定到集合时,它不会在更改集合时影响UI。

底层集合类型是否必须是ObservableCollection才能工作,或者是否可以编写自己的集合类?

日Thnx

1 个答案:

答案 0 :(得分:0)

您也可以使用具有某些扩展功能的ICollectionView进行过滤。如果您想要预制课程,请查看one available at Code Project

特别是,我注意到UI订阅了VectorChanged事件,因此您应该善于仅在评论中提到IObservableCollection

VectorChanged事件采用IVectorChangedEventArgs类型的接口,在环顾四周时我找不到具体的类。虽然创建一个并不困难。这是一个可以创建类似于您创建NotifyPropertyChangedEventArgs实例的方法。它是私有的,因为它仅用于集合类。

private sealed class VectorChangedEventArgs : IVectorChangedEventArgs
{
    public VectorChangedEventArgs(NotifyCollectionChangedAction action, object item, int index)
    {
        switch (action)
        {
            case NotifyCollectionChangedAction.Add:
            CollectionChange = CollectionChange.ItemInserted;
            break;
            case NotifyCollectionChangedAction.Remove:
            CollectionChange = CollectionChange.ItemRemoved;
            break;
            case NotifyCollectionChangedAction.Move:
            case NotifyCollectionChangedAction.Replace:
            CollectionChange = CollectionChange.ItemChanged;
            break;
            case NotifyCollectionChangedAction.Reset:
            CollectionChange = CollectionChange.Reset;
            break;
            default:
            throw new ArgumentOutOfRangeException("action");
        }
        Index = (uint)index;
        Item = item;
    }

    /// <summary>
    /// Gets the affected item.
    /// </summary>
    public object Item { get; private set; }

    /// <summary>
    /// Gets the type of change that occurred in the vector.
    /// </summary>
    public CollectionChange CollectionChange { get; private set; }

    /// <summary>
    /// Gets the position where the change occurred in the vector.
    /// </summary>
    public uint Index { get; private set; }
}