How can I make my bound WPF DataGrid sortable?
My WPF4 DataGrid is bound to a non-sortable collection - ObjectResult(of t) . I can't figure out how to instead use a sortable colle开发者_运维技巧ction such as ListCollectionView.
Details: When the application loads the user initiates a search to fill the DataGrid and other editable controls. To perform the search I'm building an ObjectQuery(of t) based on the users filter choices. The Execute method of the ObjectQuery returns and ObjectResult which I set as my CollectionViewSource.Source. In the XAML the DataGrid is bound to the CollectionViewSource which is the DataContext for the screen I've created.
System.Data.Objects.ObjectQuery<LabSample> labSamplesQuery = this.GetLabSamplesFiltered_Query(_labEntitiesContext, sampleID_LIKE, xxx_LIKE, yyy_LIKE);
System.Data.Objects.ObjectResult<LabSample> labSamples = labSamplesQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
_labSamplesCollectionViewSource.Source = labSamples;
Because the DataGrid is bound to ObjectResult(of t) it's not sortable. How can I get my query results (labSamples) into a sortable & updatable collection before asssigning it as the source of my data (CollectionViewSource.Source)?
WPF DataGrid will not be sortable becouse of deferred loading. You need to use ToList() method as follows: ..... _labSamplesCollectionViewSource.Source = labSamples.ToList(); Now datagrid should be sortable.
You can wrap your collection with an ICollectionView
and return that to your bound DataGrid
.
private ICollectionView _view;
public ICollectionView Samples
{
get
{
if (_view == null)
{
_view = CollectionViewSource.GetDefaultView(new ObservableCollection<LabSample>(labSamples));
_view.SortDescriptions.Add(new SortDescription("PropertyName", ListSortDirection.Ascending));
}
return _view;
}
}
You can also set the sorting logic within XAML. Bea has an article on achieving that here. If you make the ObservableCollection<LabSamples>
a class level variable or contained within a service holding onto the wrapped reference your changes will then be reflected in the DataGrid
.
精彩评论