.net - 反转 ListBox 项目(按 "nothing"降序排序)

标签 .net wpf sorting listbox

是否可以在 WPF 中对项目进行排序 ListBox与他们原来的顺序相反?我的意思是你可以使用 SortDescriptions按某些属性排序,但是如果我只需要以相反的顺序显示项目而没有实际字段进行排序怎么办?

注意:我不想对原始集合进行排序或克隆它等。我知道如何做到这一点,但我正在寻找一种方法来制作 ListBox这样做仅用于演示。

谢谢

最佳答案

这有点难看,但它会颠倒 listbox1 中 ListBoxItems 的顺序。您不能做显而易见的事情:使用单个临时变量并在每次循环迭代中交换两个元素。您收到一个运行时错误,“ 元素已经有一个逻辑父元素。必须先将它与旧父元素分离,然后才能将其附加到新的父元素。”。

using System;
using System.Windows;
using System.Windows.Controls;

namespace ReverseListbox
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ItemCollection items = this.listbox1.Items;
            for (int i = 0, j = items.Count - 1; i < j; i++, j--)
            {
                object tmpi = items[i];
                object tmpj = items[j];
                items.RemoveAt(j);
                items.RemoveAt(i);
                items.Insert(i, tmpj);
                items.Insert(j, tmpi);
            }
        }
    }
}

这是完整示例的 XAML:
<Window x:Class="ReverseListbox.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <ListBox Name="listbox1" Grid.Row="0">
            <ListBoxItem Content="1" />
            <ListBoxItem Content="2" />
            <ListBoxItem Content="3" />
            <ListBoxItem Content="4" />
        </ListBox>
        <Button Name="button1" Grid.Row="1" Click="Button_Click" />
    </Grid>
</Window>

关于.net - 反转 ListBox 项目(按 "nothing"降序排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/532152/

相关文章:

c# - 分布式窗口服务

c# - 如何全局指定 .net 5.0 应用程序不支持 android 和 ios

c# - 可编辑的 WPF ListView

C# .Net Core 依赖注入(inject),向构造函数注入(inject)多个参数

.net - 单操作系统特定 DLL

wpf - 鼠标悬停时更改椭圆的颜色

c# - 在桌面和 Surface (PixelSense) 1.0 上运行的 WPF 应用程序的约定

actionscript-3 - AS3 Vector.sort()不接受排序选项吗?

objective-c - localizedCaseInsensitiveCompare 似乎不适用于瑞典语字符

c++ - 映射键排序