![](/img/trans.png)
[英]How to update item in UWP ListView with AdvancedCollectionView source
[英]How can we move recent updated item on top in AdvancedCollectionView uwp
我有一個 ListView,它的 ItemSource 綁定到 AdvancedCollectionView。 該集合存儲了一些用戶的聊天消息列表。 現在,每當該用戶收到新的聊天消息時,我想將該項目移到頂部。 同樣在 WhatsApp 和 slack 應用程序中。 現在,每次收到新消息時,我都會刪除和添加項目。
所以我想知道 AdvancedCollectionView 是否有任何我可以使用的屬性,或者是否可以進行排序。
我不得不說 AdvancedCollectionView 沒有這樣的屬性可以直接做到這一點。 但您的方案的解決方法是您可以同時為 AdvancedCollectionView 應用另一個 SortDescription。 這使得可以使用新屬性將項目移到頂部。
例如,您可以在 model 中添加一個名為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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.