WPF如何将ListBox.ItemsSource转换为ObservableCollection<某些动态类型> [英] WPF How to cast ListBox.ItemsSource into ObservableCollection<some dynamic type>

查看:230
本文介绍了WPF如何将ListBox.ItemsSource转换为ObservableCollection<某些动态类型>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个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&lt;某些动态类型&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆