繁体   English   中英

x:Bind 不适用于 Listview 和 ObservableCollection

[英]x:Bind is not working with Listview and ObservableCollection

我想从 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>

但我的视图没有更新,我看不到项目。 哪里错了?

您使用 OneTime 绑定绑定到章节:

<ListView ItemsSource="{x:Bind Chapters}">

然后替换章节:

Chapters = new ObservableCollection<ChapterProperty>(await db.Chapters.ToListAsync());

x:Bind 默认为 OneTime。 也不清楚章节是否设置为发送 PropertyChanged 通知。 如果不是,那么绑定无论如何都不会在属性更改时更新。

而不是像这样在运行时创建新集合:

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM