c# - x:Bind 不适用于 Listview 和 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>

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

回答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>

相似文章

go - golang 如何从字符串中查找表情符号?

我想查找表情符号是否存在并替换为字符串(HTMLunicode)。(符文到字符串)例如,这是句子“我喜欢你哈哈哈😀你好。”这就是结果。“我喜欢你哈哈哈😀你好。”表情符号和表情符号位置是随机的。我将...

随机推荐

最新文章