在.net MAUI中添加对象时,自定义对象的数据绑定不刷新UI



我有一个MAUI应用程序。我有一个对象CommentNoteList<Note>-对象内部:

public class Comment {
public List<Note> Notes { get; set; }
...
}

现在在我的MainPage.xaml中,我想显示我的Comment的所有Notes。为此,我建立了一个<ListView>:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="VisitMaui.MainPage"
xmlns:viewmodel="clr-namespace:VisitMaui.ViewModels"
x:DataType="viewmodel:MainViewModel"
xmlns:Classes="clr-namespace:PersonalBibleindex.Classes"
xmlns:Controls="clr-namespace:VisitMaui.Controls">    
<Label Text="Notes/>
<ListView ItemsSource="{Binding Comment.Notes}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="{x:Type Classes:Note}">
<TextCell Text="{Binding Text}"></TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>

如果我手动加载Notes到我的列表,这工作得很好。但是现在我想通过点击一个按钮来动态地创建Notes:

<Button Text="Add note" Command="{Binding AddCommand}"/>

Add-函数在我的ViewModel看起来像这样:

[RelayCommand]
void Add()
{
Note MyNote = new Note();
MyNote.VerseWords = "DasWort";
MyNote.Text = "Testnotiz";
Comment.Notes.Add(MyNote);
Counter++;
}

我的问题:当我点击Add note-按钮,一个新的笔记将被添加到Comment.Notes-列表,但UI不刷新。我错过了什么?

您需要一个ObservableCollection,所以尝试将List<Note>更改为ObservableCollection<Note>

这是因为你的ViewModel类没有实现INotifyPropertyChanged接口,使视图层意识到数据的变化,请参考更新视图以响应底层视图模型或模型的变化了解更多细节。

关于如何解决这个问题,您可以参考MAUI的官方MVVM标准示例:数据绑定和MVVM,以了解如何实现INotifyPropertyChanged接口的更多细节。