在默认的排序下,当将ListBoxItem往下移动时,ListBoxItem是从其他ListBoxItem的底部移动的
如下图:
如下图:

但当往上移动时,情况则不是如此,


所以需要尝试对ListBoxItem的顺序进行反转
最后总结得到需求:将转载这些数据的条目ListBoxItem反转:
1. 这不是对数据进行了排序,而是在UI上进行排序实现的原理是ScaleTransform:改变坐标轴的变形,不仅可以进行缩放的变形,还可以进行反转的变形
第一步:改变ItemsPanel的Template,将存放ListBoxItem的容器进行上下旋转,代码如下:

1 <ListBox.ItemsPanel> 2 <ItemsPanelTemplate> 3 <StackPanel VerticalAlignment="Top" Orientation="Vertical"> 4 <StackPanel.LayoutTransform> 5 <ScaleTransform ScaleX="1" ScaleY="-1" /> 6 </StackPanel.LayoutTransform> 7 </StackPanel> 8 </ItemsPanelTemplate> 9 </ListBox.ItemsPanel>
此时运行的效果如下:

效果虽然很奇怪,但的确是上下颠倒了
然后,深入去分析一下,为什么显示的结果如此奇怪,经过分析得知,整个容器上下旋转时,ListBoxItem里的数据也跟着旋转了,
所以ListBoxItem也要进行一次旋转,(原理就是所谓的负负得正 O(∩_∩)O~)
View Code
由于反转后,上下的数据也切换了,如果还想让数据跟原来的保持一致,可以有以下几种方法:
View Code
第二种,使用ListBox的排序方法
View Code
完整的代码下载:https://yunpan.cn/cY8DSuCx5gNfh 访问密码 bd4a

1 <StackPanel.LayoutTransform> 2 <!--ScaleX="1"表示X轴不变,ScaleY="-1"表示Y轴反转,即上下颠倒--> 3 <ScaleTransform ScaleX="1" ScaleY="-1" /> 4 </StackPanel.LayoutTransform>
此时效果如下:
由于反转后,上下的数据也切换了,如果还想让数据跟原来的保持一致,可以有以下几种方法:
(这也是反转ListBox的数据,也可以叫排序)
第一种,不用ListBox的Add()而该用Insert()方法
1 for (int i = 1; i < 10; i++) 2 stus.Insert(0, new Student() { Id = i, Name = "Tommy" + i }); //保证后面加入的数据都在首位 3 //stus.Add(new Student() { Id = i, Name = "Tommy" + i });

1 lst1.Items.SortDescriptions.Add(new SortDescription("Name",ListSortDirection.Descending));//“Name”为ListBoxItem对应对象的某个属性