i want to read some data from sqlite and bind them to listview this is my codes:
public ObservableCollection<ChapterProperty> Chapters { get; set; } = new();
using var db = new AlAnvarDBContext();
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
and my 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:
<ListView ItemsSource="{x:Bind Chapters}">
then later replace Chapters:
Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());
x:Bind is OneTime by default. Also unclear if Chapters is setup to dispatch PropertyChanged notifications. 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:
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.
You should use TemplateBinding instead
https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/templatebinding-markup-extension
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.