3

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 Answers1

3

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?
}
user7116
  • 63,008
  • 17
  • 141
  • 172