【发布时间】:2021-09-27 18:16:39
【问题描述】:
添加新项目时如何对 DataView 进行排序? 我有包含 ListBox 控件的 UserControl,其中 ItemsSource 设置为 DataView。当我将新项目添加到 DataView 中时,项目总是在 ListBox 中显示为最后一个。 对 DataView 进行排序并在 ListBox 中按排序显示新项目的最佳方法是什么?
DataView ListBoxItems = new DataView();
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
DataTable dt = ..."SELECT * FROM table" //populated from database
ListBoxItems = dt.DefaultView;
ListBoxItems.Sort = "Col1 DESC, Col2 ASC";
ListBox.ItemsSource = ListBoxItems;
}
//Adding new item into DataView
DataRowView row = ListBoxItems.AddNew();
row["Col1"] = value1;
row["Col2"] = value2;
ListBoxItems.EndInit();
ListBox.SelectedItem = row;
ListBox.ScrollIntoView(row);
编辑: 我尝试了 Max Play 提供的链接的解决方案,但没有成功。 添加新项目的更新代码:
//Adding new item into DataView
DataRowView row = ListBoxItems.AddNew();
row["Col1"] = value1;
row["Col2"] = value2;
ListBoxItems.EndInit();
ListBox.Items.SortDescriptions.Clear();
ListBox.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("Col1", System.ComponentModel.ListSortDirection.Descending));
ListBox.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("Col2", System.ComponentModel.ListSortDirection.Ascending));
ListBox.SelectedItem = row;
ListBox.ScrollIntoView(row);
新项目总是在 ListBox 中最后显示,而不是首先显示(基于排序选项)。
【问题讨论】:
-
这能回答你的问题吗? How to sort in a WPF ListBox?
-
为什么你有两种排序,一种是降序,然后是升序?也许您打算将这两者结合起来?