我们如何在 AdvancedCollectionView uwp 中将最近更新的项目移动到顶部

How can we move recent updated item on top in AdvancedCollectionView uwp

我有一个 ListView,它的 ItemSource 绑定到 AdvancedCollectionView。该集合存储了一些用户聊天消息的列表。现在,每当该用户收到新的聊天消息时,我想将该项目移到顶部。在 WhatsApp 和 slack 应用程序中也是如此。 现在我每次收到新消息时都会删除和添加项目。

所以我想知道是否有 属性 我可以使用的 AdvancedCollectionView 或者是否可以排序。

不得不说,没有属性的AdvancedCollectionView可以直接做到这一点。但是您的方案的解决方法是您可以同时为 AdvancedCollectionView 应用另一个 SortDescription。这使得可以使用新的 属性.

将项目移到顶部

例如,您可以在模型中添加一个名为 Top 的新 属性,默认值为 B。当您需要将项目放在顶部时,将 Top 值更改为 A。然后应用依赖于 Top 属性.

的新排序描述

我做了一个简单的demo,你可以参考一下

代码隐藏:

 public ObservableCollection<Person> oc { get; set; }
    public MainPage()
    {
        this.InitializeComponent();

         oc = new ObservableCollection<Person>{
            new Person { Name = "Staff" ,Top="a"},
            new Person { Name = "Orchid",Top="b" },
            new Person { Name = "Tempest" ,Top="b"},
            new Person { Name = "Lamp Post",Top="b" },
            new Person { Name = "Arrow" ,Top="b"},
            new Person { Name = "Swan" ,Top="b"},
            new Person { Name = "Flame",Top="b" },
            new Person { Name = "Pearl" ,Top="b"},
            new Person { Name = "Hydra" ,Top="b"},
            new Person { Name = "Looking Glass",Top="b" },
        };

        var acv = new AdvancedCollectionView(oc, true);
        //make the Staff item always on the top
        acv.SortDescriptions.Add(new SortDescription("Top", SortDirection.Ascending));
        // sort by name
        acv.SortDescriptions.Add(new SortDescription("Name", SortDirection.Ascending));

        MyListView.ItemsSource = acv;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var person = new Person { Name = "Aardvark",Top = "b" };
        oc.Add(person);
    }

 public class Person
    {
        public string Name { get; set; }
        public string Top { get; set; }
    }

XAML:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Button Content="Click" Click="Button_Click"/>
    <ListView x:Name="MyListView" Grid.Row="1">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Person">
                <Grid>
                    <TextBlock Text="{x:Bind Name}"/>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

结果如下所示: