我使用了 http://www.thomaslevesque.com/2009/08/04/wpf-automatically-sort-a-gridview-continued/ 中找到的类。但它不提供在应用程序加载时对 ListView 列进行排序的功能。您需要先单击列才能工作。我的知识还不够先进,无法实现这一点。有人可以帮我解决这个问题吗?
最佳答案
从以下... http://www.wpf-tutorial.com/listview-control/listview-sorting/
您可以将 SortDescription
添加到 ListView
的 CollectionView
中,从而...
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(YOURLISTVIEWNAME.ItemsSource);
cv.SortDescriptions.Add(new SortDescription("COLUMNNAMETOSORT", ListSortDirection.Ascending));
所以,如果您的 ListView
名为 lv
,并且您想按 Name
排序,那么您将...
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(lv.ItemsSource);
cv.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
在您链接到的代码中,有两个函数
private static void AddSortGlyph
private static void RemoveSortGlyph
我不明白为什么您不能在添加 SortDescription
代码后手动调用 AddSortGlyph
。
事实上,还有一个 public static void ApplySort
函数...您可以直接调用它,而不是添加我首先建议的代码!
可以使用此处描述的方法来获取列... Get GridViewColumn Header value from ListView? ...但它必须在窗口激活后完成(因为标题在窗口的构造函数期间不存在)。
最后,将以下代码添加到 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;
}
}
并将其添加到您的 Window
Xaml 元素
Activated="Window_Activated"
例如
<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">
我刚刚在你的代码上测试了它......比我一直在做的所有猜测要容易得多!
关于c# - 使用类在 ListView 上实现初始排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31458719/