问题
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.
My problem is: How can I cast the ListBox.ItemsSource into a ObservableCollection.
I already tried:
ObservableCollection<object> test = listBox.ItemsSource as ObservableCollection<object>;
which does not work, because ObservableCollection doesn't support covariance.
回答1:
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?
}
来源:https://stackoverflow.com/questions/10347300/wpf-how-to-cast-listbox-itemssource-into-observablecollectionsome-dynamic-type