gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:28:11 26 4
gpt4 key购买 nike

是否可以在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com