如何将 IList 转换为 ObservableCollection<T>
How to cast IList to ObservableCollection<T>
我有一个 UserControl,它具有 ItemsSource
依赖性 属性,其类型是 IList。
如何将 IList 转换为 ObservableCollection<T>
。但是我只知道 T
的类型。我的用户控件是非通用的。我也不能改变它的参考。
这样,我想捕获 ObservableCollection
的 CollectionChanged
事件
我试过了,但是编译出错。
public IEnumerable ItemsSource
{
get { return (IList)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
private void OnItemsSourceChanged()
{
Type type = ItemsSource.GetType().GetGenericArguments().ElementAt(0);
ObservableCollection<object> list = ItemsSource.Cast<object>();
list.CollectionChanged += list_CollectionChanged;
}
CollectionChanged
在 INotifyCollectionChanged 接口中定义。 ObservableCollection<T>
实施 INotifyCollectionChanged。
因此,为了订阅事件,您可以将 ItemsSource 转换为 INotifyCollectionChanged:
var list = ItemsSource as INotifyCollectionChanged;
if (list != null)
list.CollectionChanged += list_CollectionChanged;
我有一个 UserControl,它具有 ItemsSource
依赖性 属性,其类型是 IList。
如何将 IList 转换为 ObservableCollection<T>
。但是我只知道 T
的类型。我的用户控件是非通用的。我也不能改变它的参考。
这样,我想捕获 ObservableCollection
的CollectionChanged
事件
我试过了,但是编译出错。
public IEnumerable ItemsSource
{
get { return (IList)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
private void OnItemsSourceChanged()
{
Type type = ItemsSource.GetType().GetGenericArguments().ElementAt(0);
ObservableCollection<object> list = ItemsSource.Cast<object>();
list.CollectionChanged += list_CollectionChanged;
}
CollectionChanged
在 INotifyCollectionChanged 接口中定义。 ObservableCollection<T>
实施 INotifyCollectionChanged。
因此,为了订阅事件,您可以将 ItemsSource 转换为 INotifyCollectionChanged:
var list = ItemsSource as INotifyCollectionChanged;
if (list != null)
list.CollectionChanged += list_CollectionChanged;