如何在 WPF ListBox 中排序?

How to sort in a WPF ListBox?(如何在 WPF ListBox 中排序?)
本文介绍了如何在 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 中排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)