如何在 WPF ListBox 中排序? [英] How to sort in a WPF ListBox?

查看:79
本文介绍了如何在 WPF ListBox 中排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The C# 4.0 WPF application, see the code below, shows on startup:

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

abd after clicking the Sort button with btnSort_Click() click event handler:

如何按 aaa、bbb、ccc 排序?

How can I sort in order 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>

更新:
好吧,我只是按照文章 "Sorting a WPF列表框项目"

那么,我按属性内容"排序的顺序是什么,该属性内容"在哪里,我想知道(试图将其更改为任意fff"而不是内容"得到相同,如第二张截图所示,结果?

So, what is the order by which I am sorting by a property "Content" and where is that property "Content", I wonder (tried to change it to arbitrary "fff" instead of "Content" having gotten the same, as in 2nd screenshot, results?

推荐答案

由于是对字符串列表进行排序,所以不要指定属性名(SortDescription 的第一个参数):

Since you're sorting a list of strings, don't indicate a property name (first parameter of SortDescription):

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

这篇关于如何在 WPF ListBox 中排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆