Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Datagrid.SelectedItems collection to List<T>

I Have a class like this

public class Foo
{
    public string prop1 {get;set;}
    public string prop2 {get;set;}
}

And a view model with a List<Foo>, this list is used as a Bind of one DataGrid, then in the codebehind I need to get the Datagrid.SelectedItems collection and convert it to List<Foo>

Things that i tryed:

List<Foo> SelectedItemsList= (List<Foo>)DataGrid.SelectedItems;
// OR
object p = DataGrid.SelectedItems;
List<Foo> SelectedItemsList= ((IList)p).Cast<Foo>().ToList();

All this ways compile but throw an exception at run time.

What is the proper way to cast it ?

NOTE: Base Type of DataGrid is an ObservableCollection does this made some diference ?

like image 466
Juan Pablo Gomez Avatar asked Oct 28 '13 17:10

Juan Pablo Gomez


2 Answers

Make sure to use the System.Linq namespace then :

You should be able to use :

List<Foo> SelectedItemsList = DataGrid.SelectedItems.Cast<Foo>().ToList();

or if you're not quite sure what DataGrid.SelectedItems contains :

List<Foo> SelectedItemsList = DataGrid.SelectedItems.OfType<Foo>().ToList()
like image 93
AirL Avatar answered Oct 31 '22 14:10

AirL


Try this:

DataGrid.SelectedItems.OfType<Foo>().ToList()
like image 21
gleng Avatar answered Oct 31 '22 12:10

gleng