WPF How to cast ListBox.ItemsSource into Observabl

2019-07-21 22:53发布

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条回答
乱世女痞
2楼-- · 2019-07-21 23:35

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?
}
查看更多
登录 后发表回答