简体   繁体   中英

DataGrid default column filter

Lets say we have a DataGrid which populated with 2 columns: "First Name" and "Last Name".

My goal is to sort DataGrid by LastName. It should be working when ObservableCollection (behind DataGrid) is appending or items being removed from it.

Is there some simple XAML solution or or just i have to do via the code ?

PS I aware of ICollectionView solution, but i looking for small and natural fix.

Use SortedList as your data context, and in your ViewModel implement INotifyPropertyChanged this will replace the ObservableCollection.
and with SortedList you can sort your collection for your needs...

Implementing INotifyPropertyChanged as suggested by user1763180 will only work if you call OnPropertyChanged every time you Add to the collection. ObservableCollection is convenient because you do not need to deal with the INotifyPropertyChanged interface.

The easiest way is to call

dataGridView.Sort(dataGridView.Columns[1], ListSortDirection.Ascending);

on your DataGridView .

Another option: either calling Insert or overriding the Add method to use Insert to automatically keep your collection sorted.

public void Add(string firstName, string lastName)
{
  for (int i = 0; i < _lastNames.Count; i++)
  {
    if (lastName.CompareTo(_lastNames.Items[i]) >= 0)
    {
      _lastNames.Insert(i, lastName);
      _firstNames.Insert(i, firstName);
      break;
    }
  }
}

I would skip the DataGrid and use a read only GridView ListView

This code is just hand entered and not tested but but I do something close

private ObservableCollection<person> persons;

public ObservableCollection<person> PersonsSorted { get { return persons.orderby(x => x.LastName; } } 

Bind the ListView to PersonsSorted
It will get add and delete

Use other controls to add and remove from persons.
If you edit will need to implement iNotifyPropertyChanged

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