WPF 如何强制转换 ListBox.ItemsSource 到 ObservableCollection<某种动态类型
本文关键字:动态 类型 ObservableCollection 何强制 转换 ListBox ItemsSource WPF | 更新日期: 2023-09-27 18:32:21
我写了一个允许对ListBox重新排序的行为。为了正常工作,ListBox的ItemsSource必须是ObservableCollection<...>,所以我可以调用Move(from,to)方法。
我的问题是:如何将 ListBox.ItemsSource 强制转换为 ObservableCollection。
我已经尝试过:
ObservableCollection<object> test = listBox.ItemsSource as ObservableCollection<object>;
这不起作用,因为可观察集合不支持协方差。
由于您知道要调用的方法,因此ObservableCollection<T>.Move
,您可以使用简单的反射:
var move = listBox.ItemsSource
.GetType()
.GetMethod("Move");
if (move != null)
{
move.Invoke(listBox.ItemsSource, new[] { old, new });
}
else
{
// IList fallback?
}