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()
Try this:
DataGrid.SelectedItems.OfType<Foo>().ToList()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With