I have a WPF page, where I have several ListViews
.
I want to sort my lists when clicking on headers
, for this there is no problem, but for now I make a separate function for each ListView, I would like to make a common function.
Let's say I would like to replace that :
contexte.ListeDesAssemblagesView.SortDescriptions.Clear();
contexte.ListeDesAssemblagesView.SortDescriptions.Add(monsort);
By something like :
sender.ItemsSource.SortDescriptions.Clear();
sender.ItemsSource.SortDescriptions.Add(monsort);
Edit : Here is the code of my function modified thanks to mm8.
void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
ListSortDirection direction;
ListView listView = sender as ListView;
ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource);
string header = "";
if (headerClicked.Column.DisplayMemberBinding != null)
{
header = ((System.Windows.Data.Binding)headerClicked.Column.DisplayMemberBinding).Path.Path;
}
else
{
try
{
DataTemplate cellTemplate = headerClicked.Column.CellTemplate;
Grid grid = cellTemplate.LoadContent() as Grid;
TextBlock textBlock = grid.Children.OfType<TextBlock>().FirstOrDefault();
header = BindingOperations.GetBinding(textBlock, TextBlock.TextProperty).Path.Path;
}
catch
{
}
}
string lastHeaderName = view.SortDescriptions[0].PropertyName;
string lastDirection = view.SortDescriptions[0].Direction.ToString();
if (headerClicked != null)
{
if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
{
if (header != lastHeaderName)
{
direction = ListSortDirection.Ascending;
}
else
{
if (lastDirection == "Ascending")
{
direction = ListSortDirection.Descending;
}
else
{
direction = ListSortDirection.Ascending;
}
}
if (header != "")
{
SortDescription monsort = new SortDescription(header, direction);
view.SortDescriptions.Clear();
view.SortDescriptions.Add(monsort);
}
}
}
}
If you hook up the event handler to the ListViews
in your XAML markup like this:
<ListView GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler">
...you could simply cast the sender
argument:
void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
{
ListView listView = sender as ListView;
ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource);
//...
}