Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5534

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 ?

Upvotes: 22

Views: 25980

Answers (3)

Yannick Turbang
Yannick Turbang

Reputation: 388

Here is an example i used to remove items when the user unselect an element in a ListBox.

var req = Listbox1.SelectedItems.OfType<string>().ToList().Where(c => c == item.Name).FirstOrDefault();
if (req==null)
{
    var a = MyMapView.Map.OperationalLayers.Where(c => c.Name == item.Name).FirstOrDefault();
    MyMapView.Map.OperationalLayers.Remove(a);
}

Upvotes: 0

AirL
AirL

Reputation: 1907

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()

Upvotes: 48

gleng
gleng

Reputation: 6304

Try this:

DataGrid.SelectedItems.OfType<Foo>().ToList()

Upvotes: 4

Related Questions