[英]Why doesn't ItemsSource bind to my custom CollectionChanged event
這是我經歷過的最奇怪的事情。 在Windows 8中,MS從CollectionViewSource中刪除了過濾和排序,所以我不得不構建自己的名為CollectionView<T>
。 CollectionView
具有類型為IObservableCollection<T>
的View屬性,這是我制作的自定義接口,用於保持抽象。 它的定義很簡單
public interface IObservableCollection<T> : IReadOnlyList<T>, INotifyCollectionChanged
{
}
然后,我有了實現該接口的內部類:
internal class FilteredSortedCollection<T> : IObservableCollection<T>
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public void RaiseCollectionChanged(NotifyCollectionChangedEventArgs args)
{
var copy = CollectionChanged;
if (copy != null)
copy(this, args);
}
public Func<IEnumerator<T>> RequestEnumerator { get; set; }
public Func<int> RequestCount { get; set; }
public Func<int, T> RequestItem { get; set; }
public IEnumerator<T> GetEnumerator()
{
return RequestEnumerator();
}
public int Count { get { return RequestCount(); } }
public T this[int index] { get { return RequestItem(index); } }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
事情一直到這里。 CollectionView可以正確過濾和排序,並且View可以正常工作。 除了將其綁定到ListView.ItemsSource屬性之外, 它的行為就像未實現INotifyCollectionChanged
。 沒有人聽CollectionChanged事件(已通過調試器檢查), 並且UI不會使用添加的新元素進行更新 。 但是,如果我添加一些項目,然后設置ItemsSource屬性,則UI會更新。 就像是正常的,不可觀察的列表一樣。
有人知道這里會發生什么嗎? 我嘗試刪除IObservableCollection
接口,因此FilteredSortedCollection
只是直接實現了IReadOnlyList<T>
和INotifyCollectionChanged
,但沒有成功。
您的集合需要實現IList。 我剛遇到了在我的Windows Phone應用程序中實現IList的問題,但是當我嘗試將View模型用於Windows 8應用程序時,它並沒有兌現更改的事件。
我在類中添加了IList的實現,現在一切正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.