![](/img/trans.png)
[英]Implementing INotifyCollectionChanged on a collection without indexes
[英]Implementing INotifyCollectionChanged on custom list
我目前在UWP中有一個類,該類是一堆不同類型的列表的包裝,包括我構建的自定義列表。 該包裝器需要綁定到某種列表,如ListView,ListBox,GridView等。
問題是當我嘗試實現INotifyCollectionChanged
,似乎UI元素沒有將處理程序分配給CollectionChanged
或PropertyChanged
處理程序(處理程序始終為null
)。 但是,將列表從我的自定義列表更改為ObservableCollection
似乎可以正常工作。 我缺少使UI綁定其集合更改為我的類的東西嗎?
我當前的實現看起來像
public class MyWrapperList<T> : IList<T>, INotifyPropertyChanged, INotifyCollectionChanged
{
private IEnumerable<T> _source;
// Implement all interfaces here, including my custom GetEnumerator() and all my add, insert, remove, etc classes
}
請注意,由於我希望這是一個查看原始列表的包裝器,因此我不希望像其他許多答案一樣從ObservableCollection
中插入。
編輯:您可以在GitHub上找到可復制的問題的示例: https : //github.com/nolanblew/SampleCollectionChanged/
為了有ListView
自動綁定到您的收藏,你必須實現 INotifyCollectionChange
和 IList
(注:這就是非通用的IList)。
如果您修改示例代碼,以便您的自定義列表類實現IList
:
public class MyWrapperList<T> : IList<T>, INotifyPropertyChanged, INotifyCollectionChanged, IList
{
//... all your existing code plus: (add your own implementation)
#region IList
void ICollection.CopyTo(Array array, int index) => throw new NotImplementedException();
bool IList.IsFixedSize => throw new NotImplementedException();
bool IList.Contains(object value) => throw new NotImplementedException();
int IList.IndexOf(object value) => throw new NotImplementedException();
void IList.Insert(int index, object value) => throw new NotImplementedException();
void IList.Remove(object value) => throw new NotImplementedException();
int IList.Add(object value) => throw new NotImplementedException();
public bool IsSynchronized => throw new NotImplementedException();
public object SyncRoot { get; } = new object();
object IList.this[int index] {
get => this[index];
set => this[index] = (T) value;
}
#endregion
}
然后在觸發按鈕單擊事件時設置CollectionChanged
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.