WPF如何将ListBox.ItemsSource转换为ObservableCollection<某些动态类型> [英] WPF How to cast ListBox.ItemsSource into ObservableCollection<some dynamic type>
问题描述
我写了一个Behavior,它可以对ListBox重新排序。要正常工作,ListBox的ItemsSource必须是ObservableCollection< ...>,因此我可以调用Move(from,to)方法。
I have written a Behavior which allows to reorder a ListBox. To work properly the ListBox's ItemsSource has to be an ObservableCollection<...>, so I can call the Move(from,to)-method.
我的问题是:
如何将ListBox.ItemsSource转换为ObservableCollection。
My problem is: How can I cast the ListBox.ItemsSource into a ObservableCollection.
我已经尝试过:
ObservableCollection<object> test = listBox.ItemsSource as ObservableCollection<object>;
这不起作用,因为ObservableCollection不支持协方差。
which does not work, because ObservableCollection doesn't support covariance.
推荐答案
由于您知道要调用的方法 ObservableCollection< T>。移动
,因此您可以使用简单的反射:
Since you know the method you'd like to call, ObservableCollection<T>.Move
, you can use simple reflection:
var move = listBox.ItemsSource
.GetType()
.GetMethod("Move");
if (move != null)
{
move.Invoke(listBox.ItemsSource, new[] { old, new });
}
else
{
// IList fallback?
}
这篇关于WPF如何将ListBox.ItemsSource转换为ObservableCollection<某些动态类型>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!