wpf 将 Datagrid.SelectedItems 集合转换为 List<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19641625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast Datagrid.SelectedItems collection to List<T>
提问by Juan Pablo Gomez
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 Bindof one DataGrid, then in the codebehind I need to get the Datagrid.SelectedItemscollection and convert it to List<Foo>
和一个带有 a 的视图模型List<Foo>,这个列表用作Bind一个DataGrid,然后在代码隐藏中我需要获取 Datagrid.SelectedItems集合并将其转换为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 DataGridis an ObservableCollectiondoes this made some diference ?
注意:Base Type of DataGridis anObservableCollection这有什么不同吗?
回答by AirL
Make sure to use the System.Linqnamespace then :
确保使用System.Linq命名空间然后:
You should be able to use :
您应该能够使用:
List<Foo> SelectedItemsList = DataGrid.SelectedItems.Cast<Foo>().ToList();
or if you're not quite sure what DataGrid.SelectedItemscontains :
或者如果您不太确定DataGrid.SelectedItems包含哪些内容:
List<Foo> SelectedItemsList = DataGrid.SelectedItems.OfType<Foo>().ToList()
回答by gleng
Try this:
尝试这个:
DataGrid.SelectedItems.OfType<Foo>().ToList()
回答by Yannick Turbang
Here is an example i used to remove items when the user unselect an element in a ListBox.
这是我用来在用户取消选择 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);
}

