I have a DataGrid that I'm binding to an ObservableCollection in my view model and I need to be able to sort the collection when the DataGrid is sorted to so I can use this sorted order elsewhere. I'm currently using a wrapper on the ObvservableCollection to support sorting. When the DataGrid is sorted it only sorts the displayed data and not the underlying data in the collection. The data consists of one integer column and one string column and needs to support ascending and descending sort on both. I also want to maintain the same usage as the standard DataGrid sort where you click a column header and it toggles between ascending and descending sort. I'm relatively new to WPF so I don't know all the ins and outs of data and command binding, but I would think there would be a way to accomplish what I want to do. Here is a sample xaml to illustrate my view set up.
<DataGrid ItemsSource="{Binding mySource}"
Name="myDataGrid"
CanUserResizeRows="False"
AutoGenerateColumns="False"
HeadersVisibility="Column" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Header 1" CanUserSort="True" SortMemberPath="firstValue">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding firstValue}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Header 2" Width="*" CanUserSort="True" SortMemberPath="secondValue">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding secondValue}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
The source data is of a type something like:
public class myType
{
public int firstValue { get; set; }
public string secondValue { get; set; }
// some functions and variables...
}
Now, like I said above, I need access to the items in the collection in their sorted order, but it does not need to specifically be an ObservableCollection. As long as I can iterate through the items in the collection in whatever the current order is when I access them, all is good. I was thinking maybe a ListCollectionView or something. I also don't want the collection to re-sort itself when new items are added to the collection. Any new items should just be added to the end of the collection as would normally happen.
Any ideas?
Best Answer
The
DataGrid
uses an underlyingICollectionView
based on the DataSource, so if you directly bind aICollectionView
you can access the sorted values as theDataGrid
will directly change theICollectionView
when sorting.Small Example:
Code:
Xaml: