Skip to main content
 首页 » 编程设计

c#之如何在 ObservableCollectionT> 中使用 GetType 返回的类型

2024年02月13日9findumars

我想将 WPF dataGrid 的 ItemSource 转换为 ObservableCollection,但我不知道其元素的类型,所以我想用这段代码来获取类型:

 var returnedType = dg.ItemsSource.AsQueryable().ElementType; 

并在这里使用 returnedType:

var sourceCollection = (ObservableCollection<???>)dg.ItemsSource; 

更清楚地说,我想将它转换为ObservableCollection,因为我需要使用它的CollectionChanged。而且我不能在这里使用泛型类型,因为我想使用它在自定义 DataGrid 中。

请您参考如下方法:

ObservableCollection<T>实现 INotifyCollectionChanged 接口(interface)和你需要的事件在这个接口(interface)上定义。所以你可以这样写代码:

var sourceCollection = (INotifyCollectionChanged)dg.ItemsSource; 
sourceCollection.CollectionChanged += ... your delegate here ...