我想从 sqlite 读取一些数据并将它们绑定到 listview 这是我的代码:
public ObservableCollection<ChapterProperty> Chapters { get; set; } = new();
using var db = new AlAnvarDBContext();
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
和我的 xaml
<ListView ItemsSource="{x:Bind Chapters}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="tables:ChapterProperty">
<StackPanel>
<TextBlock Text="{x:Bind Name}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
但我的视图没有更新,我看不到项目。哪里错了?
回答1
您使用 OneTime 绑定绑定到章节:
<ListView ItemsSource="{x:Bind Chapters}">
然后替换章节:
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
x:Bond 默认为一次性。也不清楚章节是否设置为发送 PropertyChanged 通知。如果不是,那么绑定无论如何都不会在属性更改时更新。
回答2
而不是像这样在运行时创建新集合:
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
...您应该修改已经存在的集合:
var chapters = await db.Chapters.ToListAsync();
Chapters.Clear();
if (chapters != null)
foreach (var chapter in chapters)
Chapers.Add(chapter);
删除 setter 以确保您的初始集合永远不会被替换:
public ObservableCollection<ChapterProperty> Chapters { get; } = new();
如果您在每次更新时将集合替换为另一个集合,则首先没有理由使用 ObservableCollection<T>
。