【发布时间】:2020-10-22 11:22:21
【问题描述】:
我使用来自 Windows Community Toolkit 的 AdvanceCollectionView 作为 XAML ListView 的源,以允许排序和过滤。我在更新 ListView 时遇到问题。
为了重现这个问题,我创建了一个简单的Person 类。在MainPage XAML 中,我有一个ListView MyXAMLList 和一个Button EditButton。在MainPage 代码中,我有一个ObservableCollection<Person> MyPersonList 和AdvancedCollectionView MyPersonACV。在Page_Loaded 事件中,我将一个人添加到列表中,并使用 AdvancedCollectionView 作为列表视图的来源:
Person p = new Person
{
Name = "John",
Age = 35
};
MyPersonList.Add(p);
MyPersonACV = new AdvancedCollectionView(MyPersonList, true);
MyXAMLList.ItemsSource = MyPersonACV;
这行得通,我可以在列表中看到 John。
在EditButton 代码中,我尝试更新列表中的项目,但这不起作用。 ObservableCollection 和 AdvancedCollectionView 都已更新,但 XAML 列表仍显示旧名称“John”而不是“Mary”。
MyPersonList[0].Name = "Mary";
Debug.WriteLine(MyPersonList[0].ToString());
Debug.WriteLine(MyPersonACV[0].ToString());
我已尝试更新 MyXAMLList.SelectedItem,但结果相同:
Person p = (Person)MyXAMLList.SelectedItem;
p.Name = "Mary";
我也尝试添加MyPersonACV.Refresh();,但没有帮助。
我做错了什么?如何更新列表中的项目?
完整代码如下
人物类:
class Person
{
public string Name {get; set;}
public int Age { get; set; }
public override string ToString()
{
return Name;
}
}
主页 XAML:
<Page
x:Class="App3.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App3"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
Loaded="Page_Loaded">
<Grid>
<StackPanel Orientation="Vertical">
<ListView Height="Auto" Width="Auto" x:Name="MyXAMLList" SelectionMode="Single" IsItemClickEnabled="True"/>
<StackPanel Orientation="Horizontal">
<Button x:Name="EditButton" Content="Edit" Click="EditButton_Click"/>
</StackPanel>
</StackPanel>
</Grid>
</Page>
主页cs:
using Microsoft.Toolkit.Uwp.UI;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App3
{
public sealed partial class MainPage : Page
{
private ObservableCollection<Person> MyPersonList = new ObservableCollection<Person>();
private AdvancedCollectionView MyPersonACV;
public MainPage()
{
this.InitializeComponent();
}
private void EditButton_Click(object sender, RoutedEventArgs e)
{
//Change name
MyPersonList[0].Name = "Mary";
//Person p = (Person)MyXAMLList.SelectedItem;
//p.Name = "Mary";
Debug.WriteLine(MyPersonList[0].ToString());
Debug.WriteLine(MyPersonACV[0].ToString());
//MyPersonACV.Refresh();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//create person
Person p = new Person
{
Name = "John",
Age = 35
};
//add to list
MyPersonList.Add(p);
//set up ListView source
MyPersonACV = new AdvancedCollectionView(MyPersonList, true);
MyXAMLList.ItemsSource = MyPersonACV;
}
}
}
【问题讨论】:
标签: c# xaml listview uwp windows-community-toolkit