如何解决C# WPF - 在 DataView 中添加新项目后显示在 ListBox 中排序的项目
如何在添加新项目时对 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 的最后,而不是最先显示(基于排序选项)。
解决方法
找到解决方案,现在按预期工作。
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
BindingListCollectionView cv = (BindingListCollectionView)CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
DataRowView row = (DataRowView) cv.AddNew();
row["Col1"] = value1;
row["Col2"] = value2;
cv.CommitNew();
cv.SortDescriptions.Clear();
cv.SortDescriptions.Add(new SortDescription("Col1",ListSortDirection.Descending));
cv.SortDescriptions.Add(new SortDescription("Col2",ListSortDirection.Ascending));
ListBox.SelectedItem = row;
ListBox.ScrollIntoView(row);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。