Вы можете сделать это, добавив System.ComponentModel пространство имен, например:
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
, затем внутри CollectionViewSource XAML добавьте новый SortDescription вот так:
<CollectionViewSource … >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Column1"/>
<scm:SortDescription PropertyName="Column2"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
это будет сортировать сетку данных по столбцу1, столбцу 2.
Редактировать:
и сделать это с помощью кода C # позадидовольно просто:
private void btnSort_Click(object sender, RoutedEventArgs e)
{
System.Windows.Data.CollectionViewSource myViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("The_ViewSource_Name")));
myViewSource.SortDescriptions.Add(new SortDescription("Column1", ListSortDirection.Ascending));
myViewSource.SortDescriptions.Add(new SortDescription("Column2", ListSortDirection.Ascending));
}
Edit2:
Временное решение может быть сделано, чтобы перехватить заголовок столбца при щелчке левой кнопкой мыши и предотвратить сортировку сетки по этому столбцу, как это:
- Отключить свойство сетки с именем CanUserSortColumns
![enter image description here](https://i.stack.imgur.com/w5HsV.jpg)
Добавить этот код вgrid Событие PreviewMouseLeftButtonUp:
private void myDataGrid_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) &&
!(dep is DataGridCell) &&
!(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
if (dep is DataGridColumnHeader)
{
DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
// check if this is the wanted column
if (columnHeader.Column.Header.ToString() == "The_Wanted_Column_Title")
{
System.Windows.Data.CollectionViewSource myViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("myViewSource")));
myViewSource.SortDescriptions.Clear();
myViewSource.SortDescriptions.Add(new SortDescription("Column1", ListSortDirection.Ascending));
myViewSource.SortDescriptions.Add(new SortDescription("Column2", ListSortDirection.Ascending));
}
else
{
//usort the grid on clicking on any other columns, or maybe do another sort combination
System.Windows.Data.CollectionViewSource myViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("myViewSource")));
myViewSource.SortDescriptions.Clear();
}
}
}
Вы можете изменить и расширить этот код в соответствии с вашими требованиями.