Tower
Tower

Reputation: 102945

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

Upvotes: 2

Views: 3035

Answers (2)

Tommy
Tommy

Reputation: 131

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

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

Otherwise,

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

Upvotes: 2

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

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.

Upvotes: 6

Related Questions