在一些允许用户自定义栏目顺序的 app(如:凤凰新闻、网易云音乐等),我们可以方便地拖拽列表项来完成列表的重新排序,进而完成对栏目顺序的重排。这个功能很人性化,而实现起来其实很简单(甚至都不用写什么后台代码),只有三步。
首先,我们需要让冰箱的大门敞开,也就是允许我们进行拖拽的相关操作。以 ListView 为例,注意下面几个属性。
- 1 <StackPanel>
- 2 <ListView x:Name="list"
- 3 AllowDrop="True"
- 4 CanReorderItems="True"
- 5 IsSwipeEnabled="True">
- 6 <ListView.ItemContainerStyle>
- 7 <Style TargetType="ListViewItem">
- 8 <Setter Property="Background" Value="Gray"/>
- 9 <Setter Property="Foreground" Value="White"/>
- 10 <Setter Property="Margin" Value="4"/>
- 11 </Style>
- 12 </ListView.ItemContainerStyle>
- 13 </ListView>
- 14 <Button Click="Button_Click">Show Items</Button>
- 15 <TextBlock x:Name="txt"/>
- 16 </StackPanel>
AllowDrop 属性允许元素进行拖动,它继承自 UIElement 基类,为所有可视元素支持。
CanReorderItems 属性继承自 ListViewBase 基类,允许列表控件的项可以重新排序。
Setting to false disables some default touch interactions, so it should be set to true when these interactions are needed. For example:
You typically set to false to disable animations when items in the view don't support interactions that use the gesture, like deselecting, dragging, and reordering. Disabling the animation when it's not needed can improve the performance of your app.
(有趣的是最后一段:当列表不允许轻扫手势(撤销选定,拖动,拖拽重排)时,我们可以 "显式" 地将 IsSwipeEnabled 属性设置为 False 来提升应用的性能。)
前台 ok 后,我们就可以在后台加点东西,把我们的排序逻辑(其实并没有,微软已经写好了)添加进去。这个 demo 里,我用了一个按钮和一个文本框来观察重排的结果。如下:
- 1 public sealed partial class MainPage : Page
- 2 {
- 3 public MainPage()
- 4 {
- 5 this.InitializeComponent();
- 6 for (int i = 0; i < 10; i++)
- 7 {
- 8 list.Items.Add($"-----THIS IS ITEM {i}-----");
- 9 }
- 10 }
- 11
- 12 private void Button_Click(object sender, RoutedEventArgs e)
- 13 {
- 14 txt.Text = string.Empty;
- 15 foreach (var item in list.Items)
- 16 {
- 17 txt.Text += item.ToString()[18] + " ";
- 18 }
- 19 }
- 20 }
这样,重新排序后,点击按钮,我们即可观察到结果了。
把大象(?)装进去之后,最后就是我们的收尾工作了。显然,刚才的列表只是一个中间的载体,是我们待排序栏目的简单显示。一般而言,这个 listview 会安置在 contentdialog 或是 popup 里,那么怎么在重排后立即让父页面上的栏目得到相应,进行重排呢?我们用个预定义的委托即可,加在刚才的后台代码里(冰箱能装的东西其实挺多的)。
- public Action action;
然后在父页面注册方法,比如:
- 1 btn.Click += async(s, e) = >2 {
- 3
- var dialog = new Dialogs.Sort();
- 4 dialog.action += async() = >{
- await sortagain();
- };
- 5 await dialog.ShowAsync();
- 6
- };
大功告成!
来源: http://www.cnblogs.com/DaweiX/p/6427637.html