1

I have a MAUI app. I have an object Comment with a List<Note> of Note-objects inside:

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

Now in my MainPage.xaml I want to display all Notes of my Comment. For this I have built a <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>

If I load Notes into my List manually this works fine. But now I want to create Notes dynamically by clicking on a button:

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

Whereas the Add-function in my ViewModel looks like this:

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

My problem: When I click on the Add note-Button, a new note will be added to Comment.Notes-List, but the UI doesn't refresh. What am I missing?

OttherCreek
  • 615
  • 1
  • 6
  • 18
  • 1
    You could refer to [Populate a ListView with data](https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/listview?view=net-maui-7.0#populate-a-listview-with-data) – Liqun Shen-MSFT Mar 31 '23 at 01:47

2 Answers2

2

You need an ObservableCollection, so try changing List<Note> to ObservableCollection<Note>

davmos
  • 9,324
  • 4
  • 40
  • 43
2

This is because your ViewModel class does not implement the INotifyPropertyChanged interface to make the View layer aware of data changes, please refer to Updating views in response to changes in the underlying view model or model for more details.

For how to solve this problem, you could refer to MAUI's official MVVM standard example: Data binding and MVVM for more details about how to implement the INotifyPropertyChanged interface.

Alec - MSFT
  • 121
  • 4