如何在WPF ListBox中排序?

C#4.0 WPF应用程序,请参阅下面的代码,在启动时显示:

<img src="http://sofzh.miximages.com/c%23/HK28Y.jpg" alt=" ListBox 的初始顺序”>

使用btnSort_Click()单击事件处理程序单击排序按钮后的abd:

排序后的ListBox

我如何按顺序排序aaa,bbb,ccc?

C#代码:

 public MainWindow() { InitializeComponent(); listBox1.Items.Add("ccc"); listBox1.Items.Add("aaa"); listBox1.Items.Add("bbb"); } private void btnSort_Click(object sender, RoutedEventArgs e) { listBox1.Items.SortDescriptions.Add( new System.ComponentModel.SortDescription("Content", System.ComponentModel.ListSortDirection.Ascending)); } private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e) { listBox1.Items.RemoveAt (listBox1.Items.IndexOf(listBox1.SelectedItem)); } 

XAML:

    

更新:
好吧,我只是按照文章“排序WPF ListBox项目”

那么,我按照属性“内容”排序的顺序是什么,以及该属性“内容”在哪里,我想知道(试图将其改为任意“fff”而不是“内容”已经变得相同,如第二个截图,结果?

由于您要对字符串列表进行排序,因此不要指明属性名称(SortDescription的第一个参数):

 listBox1.Items.SortDescriptions.Add( new System.ComponentModel.SortDescription("", System.ComponentModel.ListSortDirection.Ascending)); 

对wpfcombobox或列表框进行排序很容易 – 但请记住包含Imports System.ComponentModel

简单地按字母顺序排序

 MylistBox.Items.SortDescriptions.Add( New SortDescription("", ListSortDirection.Ascending)) 

要么

 MyComboBox.Items.SortDescriptions.Add( New SortDescription("", ListSortDirection.Ascending)) 
 YOULISTBOX.Items.SortDescriptions.Clear(); YOULISTBOX.Items.SortDescriptions.Add( new System.ComponentModel.SortDescription("NAME", System.ComponentModel.ListSortDirection.Ascending)); 

确保每次更新

附加信息:

您排序的项目可能是任何DependencyProperty 。 因此,假设您有一个自定义类的ObservableCollection ,该类绑定到ListBox控件的ItemsSource 。 自定义类可以具有任意数量的依赖项属性,您可以将它们用于排序。 您只需将依赖项属性的名称(作为string )放在新的SortDescription参数中。

将多个SortDescription添加到控件将执行多变量排序。

依赖项属性可以表示任何类型的变量,而不仅仅是字符串。 我有一个例子,我首先通过bool排序,然后通过int排序,最后通过DateTime排序。