简体   繁体   中英

How to Linq through DataGrid SelectedItems in WPF?

I am trying to do:

bool hasXItems = (grid.SelectedItems as IEnumerable<Y>).Any(i => ((Y) i).IsX);

This does not seem to work (result of casting is null ). How can I query the DataGrid.SelectedItems with Linq?

This is the property I'm querying: http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.multiselector.selecteditems(v=vs.90).aspx

I cant make out from your comment what you want to do but you can use LINQ this way.

DataGridRow[] results = datagrid.SelectedItems
                                .OfType<DataGridRow>()
                                .Where(x => ((bool)x.IsFocused))
                                .ToArray();

It will iterate through all selected Rows and return that rows which are focused.

This query has 4 sections

  1. datagrid.SelectedItems . This line will give all selected rows as a list because SelectedItems returns an IList object.

  2. .OfType<DataGridRow>() . This line will return all selected rows returned from line 1 as DataGridRow.

  3. .Where(x => ((bool)x.IsFocused)) . This line will iterate over all DataGridRows returned from Line 2 to find which rows is focused.

  4. .ToArray() . This line will convert all of DatagridRows which are focused returned by Line 3 to Array and put it in the results variable.

If your .IsX() means "is X",

grid.SelectedItems.OfType<X>().Any();

Otherwise,

grid.SelectedItems.OfType<Y>().Any(item => item.IsX());

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