简体   繁体   中英

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 ?

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

尝试这个:

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM