I used the class found at http://www.thomaslevesque.com/2009/08/04/wpf-automatically-sort-a-gridview-continued/. But it doesn't provide the ability to sort the ListView columns when the application loads. You need to click the columns before it works. My knowledge hasn't advanced enough to be able to implement this. Can anybody help me with this?
1 Answers
From the following ... http://www.wpf-tutorial.com/listview-control/listview-sorting/
You can add SortDescription
s to the ListView
's CollectionView
, thus ...
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(YOURLISTVIEWNAME.ItemsSource);
cv.SortDescriptions.Add(new SortDescription("COLUMNNAMETOSORT", ListSortDirection.Ascending));
so, if your ListView
is called lv
, and you want to sort by Name
then you would have ...
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(lv.ItemsSource);
cv.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
In that code you linked to, there are two functions
private static void AddSortGlyph
private static void RemoveSortGlyph
I don't see any reason why you can't call AddSortGlyph
manually after the add SortDescription
code.
In fact there is also a public static void ApplySort
function ... you could just call that instead of adding the code i first suggested!
Getting the columns can be done using the method described here ... Get GridViewColumn Header value from ListView? ... but it must be done after the window has been activated (because the headers don't exist during the window's constructor).
Ultimately, add the following code to you MainWindow.xaml.cs
private void Window_Activated(object sender, EventArgs e)
{
List<GridViewColumnHeader> headers = GetVisualChildren<GridViewColumnHeader>(DownloadList).ToList();
GridViewSort.ApplySort(DownloadList.Items, "File Name", DownloadList, headers[10]);
}
public static IEnumerable<T> GetVisualChildren<T>(DependencyObject parent) where T : DependencyObject
{
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
yield return (T)child;
foreach (var descendant in GetVisualChildren<T>(child))
yield return descendant;
}
}
and add this to your Window
Xaml element
Activated="Window_Activated"
eg
<Window x:Class="Mackerel_Download_Manager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:p="clr-namespace:Mackerel_Download_Manager.Properties"
xmlns:util="clr-namespace:Wpf.Util"
Title="Mackerel Download Manager" Height="Auto" Width="Auto" Activated="Window_Activated">
I just tested it on your code ... much easier than all this guessing I've been doing!

- 1
- 1

- 3,250
- 2
- 15
- 38