WPF Unable to cast object of type 'System.Windows.Controls.SelectedItemCollection' to type 'System.Collections.Generic.IList`1[T]'.'

SelectedItems convert to IList as below failed;

IList<Book> collection2 = (IList<Book>)obj;

 

System.InvalidCastException
  HResult=0x80004002
  Message=Unable to cast object of type 'System.Windows.Controls.SelectedItemCollection' to type 'System.Collections.Generic.IList`1[WpfApp397.Book]'.
  Source=WpfApp397
  StackTrace:

 

 

The solution is below

 System.Collections.IList items = (System.Collections.IList)obj;
 var collection = items.Cast<Book>(); 

 

System.Windows.Controls.SelectedItemCollection ToList<T>

System.Collections.IList items = (System.Collections.IList)obj;
var collection = items.Cast<Book>()?.ToList();

  

 

posted @ 2024-09-22 19:42  FredGrit  阅读(70)  评论(0)    收藏  举报