x:Bind is not working with Listview and ObservableCollection

257 Views Asked by At

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?

3

There are 3 best solutions below

1
Abort_Retry On
0
Kevin Gallahan On

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.

0
mm8 On

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.