如何在WPF ListBox中进行排序?

10

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

<code>ListBox</code>中初始顺序

点击Sort按钮后,使用btnSort_Click()单击事件处理程序,如下所示:

排序后的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:

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox Height="100" HorizontalAlignment="Left" Margin="8,43,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" MouseDoubleClick="listBox1_MouseDoubleClick" />
        <Button Content="Sort" Height="23" HorizontalAlignment="Left" Margin="140,94,0,0" Name="btnSort" VerticalAlignment="Top" Width="75" Click="btnSort_Click" />
    </Grid>
</Window>

更新:
好的,我只是遵循了这篇文章“对 WPF ListBox 项进行排序”

所以,我按照“Content”属性排序,那么这个属性“Content”在哪里呢?我想知道(试图将其更改为任意的“fff”而不是“Content”,但得到了相同的结果,如第2张截图所示)。

4个回答

28

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

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

我不确定你现在具体在问什么……将代码更改为我的建议是否解决了这个问题? - Blachshma
它确实起作用了。我想了解SortDescription()方法的第一个参数是什么,为什么在提供任意的propertyName后不会出现错误,以及为什么顺序会改变(根据哪些排序规则)? - Fulproof
好的,它确实会出现错误。如果您使用任意属性名称,例如 fff 并在 Visual Studio 中打开您的 输出窗口,您将看到一个绑定错误,如下所示:System.Windows.Data Error: 40 : BindingExpression path error: 'fff' property not found on 'object' ''String' (HashCode=536926232)'。 - Blachshma
谢谢。我没注意到那个错误!但如果它出现了错误,为什么项目的顺序会发生改变?我猜想是否被重新排序了? - Fulproof

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

为了确保每次更新,您需要进行以下操作。

5

很容易对WPF ComboBox或ListBox进行排序 - 但请记得包含导入System.ComponentModel

要按字母顺序排序,只需

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

或者

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

3

附加信息:

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

向控件添加多个SortDescription会执行多变量排序。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接