【问题标题】:Reversing ListBox items (descending sort by "nothing")反转 ListBox 项(按“无”降序排序)
【发布时间】:2009-02-10 12:46:50
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: .net wpf sorting listbox


    【解决方案1】:

    这有点难看,但它会颠倒 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>
    

    【讨论】:

      【解决方案2】:

      一个便宜的答案是向数据对象添加一个新的整数字段,并为每个项目增加它。然后你可以在这个字段上反向排序。我知道这可能不是一个可行的解决方案。

      如果您使用集合视图进行排序,我相信您总是必须根据某些属性或条件进行排序。排序将基于实现 IComparer 的比较对象。此接口比较两个对象并确定哪个更大。除非您有某种方法可以通过比较它们来确定如何订购两个项目,否则您无法反转排序。

      【讨论】:

      • 是的,添加一个可以从原始集合返回类似 IndexOf 的人为属性也是我的第一个想法。但它看起来有点难看,而且,正如你所说,便宜。但似乎这就是我要做的。
      【解决方案3】:

      不久前我遇到了类似的问题。我最终以类似于 Josh G 的帖子的方式解决了它,但使用了一些封装以避免污染域对象。

      this discussion thread

      我用于仅由 UI 使用的集合(例如日志消息)的另一种方法是首先通过 collection.Insert(0, item); 以相反的顺序插入它们。

      【讨论】:

        猜你喜欢
        • 2016-05-08
        • 2022-10-15
        • 2017-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        相关资源
        最近更新 更多