You can do this by adding System.ComponentModel namespace like this:
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
then inside the CollectionViewSource XAML add new SortDescriptions like this:
<CollectionViewSource … >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Column1"/>
<scm:SortDescription PropertyName="Column2"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
this will sort datagrid on column1,column2.
Edit:
also doing this using C# code behind is pretty easy :
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:
Workaround can be made to catch the column header left mouse click event and prevent the grid from sort on that column like this:
- Disable grid property named
CanUserSortColumns
Add this code to the grid
PreviewMouseLeftButtonUp event :
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();
}
}
}
You can modify and expand this code to achieve your requirements.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…