[英]x:Bind is not working with Listview and ObservableCollection
i want to read some data from sqlite and bind them to listview this is my codes:我想从 sqlite 读取一些数据并将它们绑定到 listview 这是我的代码:
public ObservableCollection<ChapterProperty> Chapters { get; set; } = new();
using var db = new AlAnvarDBContext();
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
and my xaml和我的 XAML
<ListView ItemsSource="{x:Bind Chapters}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="tables:ChapterProperty">
<StackPanel>
<TextBlock Text="{x:Bind Name}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
but my view is not updated and i cant see items.但我的视图没有更新,我看不到项目。 where is wrong?
哪里错了?
You bind to Chapters using a OneTime binding:您使用 OneTime 绑定绑定到章节:
<ListView ItemsSource="{x:Bind Chapters}">
then later replace Chapters:然后替换章节:
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
x:Bind is OneTime by default. x:Bind 默认为 OneTime。 Also unclear if Chapters is setup to dispatch PropertyChanged notifications.
也不清楚章节是否设置为发送 PropertyChanged 通知。 If it isn't, then the binding wouldn't update on a property change anyways.
如果不是,那么绑定无论如何都不会在属性更改时更新。
Instead of creating a new collection at runtime like this:而不是像这样在运行时创建新集合:
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
...you should modify the already existing collection: ...您应该修改已经存在的集合:
var chapters = await db.Chapters.ToListAsync();
Chapters.Clear();
if (chapters != null)
foreach (var chapter in chapters)
Chapers.Add(chapter);
Remove the setter to make sure that your initial collection is never replaced:删除 setter 以确保您的初始集合永远不会被替换:
public ObservableCollection<ChapterProperty> Chapters { get; } = new();
If you replace the collection with another one each on each update, there is no reason to use an ObservableCollection<T>
in the first place.如果在每次更新时将集合替换为另一个集合,则首先没有理由使用
ObservableCollection<T>
。
You should use TemplateBinding instead您应该改用 TemplateBinding
https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/templatebinding-markup-extension https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/templatebinding-markup-extension
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.