微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C# WPF - 在 DataView 中添加新项目后显示在 ListBox 中排序的项目

如何解决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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?