c# - 如何默认排序wpf listview

标签 c# wpf listview

我在 this article 之后对我的 ListView 实现了排序.当窗口打开时,如何让我的列表默认排序?我试过:

public MainWindow()
        {
            InitializeComponent();
            SortCustomerList("CustomerName", ListSortDirection.Ascending);
        }

...但我收到“调用目标已抛出异常”...内部异常为“未将对象引用设置为对象的实例。”

[编辑] 我按照建议将对 sort 的调用移至加载的事件,但我仍然遇到异常?排序方法和加载的事件如下所示:

private void SortCustomerList(string sortBy, ListSortDirection direction)
{
   ICollectionView dataView = CollectionViewSource.GetDefaultView(customersListView.ItemsSource);

   dataView.SortDescriptions.Clear();
   SortDescription sd = new SortDescription(sortBy, direction);
   dataView.SortDescriptions.Add(sd);
   dataView.Refresh();
}

private void mainWindow_Loaded(object sender, RoutedEventArgs e)
{
   SortCustomerList("CustomerName", ListSortDirection.Ascending);
}

Clear() 方法失败。

感谢您的任何建议。

最佳答案

您无法从 WPF 中的构造函数访问控件,它们未使用其数据等进行初始化。我认为 Loaded 事件是您想要使用的,但请在此处检查其他生命周期事件:http://msdn.microsoft.com/en-us/library/ms754221.aspx了解更多信息。

关于c# - 如何默认排序wpf listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4634754/

相关文章:

c# - 我可以将 Unity 场景公开为 Web 服务吗?

c# - Azure:使用 Full-IIS 进行 Web 角色内通信 (netTcpBinding)

c# - 从控制台应用程序从网站读取 XML 文件

wpf - <i : Interaction. Behavior> 选项不适用于应用行为

java - Android Listview可点击textview冲突

java - 使用字符串的 ListView

c# - 检查数组中的子字符串是否存在 C#

wpf - 如何刷新 WPF DataGrid?

wpf - 对树的不同级别使用不同的模板

javascript - Android 开发 - 在正常代码运行之前获取异步任务的结果