Erik
Erik

Reputation: 2436

WPF datagrid: sort a column programatically the MVVM way?

I have a WPF application using a WPF-Datagrid. I can click on the column header to sort columns, which works automatically. What I want is to programatically select a column at program start which is then sorted. Or to put it another way: I want to pretend a user has clicked the column header, but do it programatically, the MVVM way, omitting changes in the code behind. Is there any solution for that?

Upvotes: 2

Views: 4688

Answers (2)

Alex
Alex

Reputation: 1461

I guess the "MVVM Way" of doing this is binding your DataGrid to a CollectionView which represents your objects collection and allows you to manage sorting via SortDescription property.

For example in your viewmodel you have a collection of objects:

private ObservableCollection<Entity> _entityCollection = null;
public ObservableCollection<Entity> EntityCollection
{
    get
    {
        return _entityCollection;
    }
    set
    {
        _entityCollection = value;
        RaisePropertyChanged("EntityCollection");
        RaisePropertyChanged("CollectionView");
    }
}

Note the RaisePropertyChanged("CollectionView") above: when your collection changes, the view should be notified that the collectionview has changed as well.

So instead of binding your datagrid directly to collection you define a read-only collectionview property like this:

private CollectionView _collectionView = null;
public CollectionView CollectionView
{
    get
    {
        _collectionView = (CollectionView)CollectionViewSource.GetDefaultView(EntityCollection);
        if (_collectionView != null)
            _collectionView.SortDescriptions.Add(new SortDescription("PropertyName", ListSortDirection.Ascending));
        return _collectionView;
    }
}

Then you bind your datagrid:

<DataGrid ItemsSource="{Binding Path=CollectionView}">

Finally if you want to change the property by which the collection is sorted you should clear the collectionview's sortdescriptions and add a new one like this:

_collectionView.SortDescriptions.Clear();
_collectionView.SortDescriptions.Add(new SortDescription("NewPropertyName", ListSortDirection.Ascending));

Upvotes: 7

Muhammad Saqib
Muhammad Saqib

Reputation: 124

you can do it by using Linq query if you have list and if you are using DataTables the you can use MyRows = myTable.Select(strExpr, strSort);

First you have to select the column you want to sort with and then at viewmodel you can can use either LINQ ormyTable.Select(strExpr, strSort)

Example code

 switch(columnname)
    {
    case "name":
    break;

    case "FatherName"
    break;
    }

Upvotes: 0

Related Questions