2012-04-27 30 views
2

我已經寫了一個允許重新排列ListBox的行爲。爲了正常工作,ListBox的ItemsSource必須是ObservableCollection < ...>,所以我可以調用Move(from,to)方法。我的問題是: 如何將ListBox.ItemsSource轉換爲ObservableCollection。WPF如何將ListBox.ItemsSource轉換爲ObservableCollection <一些動態類型>

我已經嘗試過:

ObservableCollection<object> test = listBox.ItemsSource as ObservableCollection<object>; 

這是不行的,因爲的ObservableCollection不支持協方差。

+0

是你的問題,因爲你知道'listBox.ItemsSource'是* IList的的'一些*類型',但你只是不知道什麼在運行時? – user7116 2012-04-27 08:43:06

+0

我只能在運行時才能得到列表的類型。 – JensPfister1 2012-04-27 08:44:32

+0

編輯:我需要的列表是一個ObservableCollection ,而不是IList JensPfister1 2012-04-27 08:52:33

回答

2

既然你知道你想打電話,ObservableCollection<T>.Move的方法,你可以使用簡單的反射:

var move = listBox.ItemsSource 
        .GetType() 
        .GetMethod("Move"); 
if (move != null) 
{ 
    move.Invoke(listBox.ItemsSource, new[] { old, new }); 
} 
else 
{ 
    // IList fallback? 
} 
+0

默認情況下,我使用IList方法,但您的答案也是(髒)不錯的方法! – JensPfister1 2012-04-27 09:20:11

相關問題