我在 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/