WPF How to cast ListBox.ItemsSource into ObservableCollection<some dynamic type>

拜拜、爱过 提交于 2019-12-12 21:03:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!