Search code examples
c#xamlxamarin.forms

How to call the refresh task on appearing of the V from VM


I have some NoteItem objects, which I store in DB. I have edited them in the EditingPage, and they are in DB already, that works. But when I go back to the MainPage, I want to call the Task Refresh() to display the new NoteItem object, which I added to my DB. How can I do it?

Refresh Task from NoteItemsViewModel.cs (used in MainPage)

public AsyncCommand RefreshCommand { get; }
        public async Task Refresh()
        {
            await Task.Delay(2000);
            NoteItems.Clear();
            var NoteItemsBeingRefreshed = await Service.GetNotesFromDB();
            NoteItems.AddRange(NoteItemsBeingRefreshed);

            //for debugging
            foreach (var noteItem in NoteItems)
            {
                Console.WriteLine(noteItem.Id);
                Console.WriteLine(" " + noteItem.Text);
            }

        }

As I see, not all the people understood my problem. First what I want to say, NoteItems is ObservableRangeCollection. Second, the problem was not to display the update, but to update Items in this collection from SQL Database that I have.

MainPage.xaml

<ListView 
                x:Name="NoteItemsList" 
                ItemsSource="{Binding NoteItems}" 
                Margin="0"
                FlexLayout.AlignSelf="Start"
            >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell >
                            <FlexLayout JustifyContent="SpaceBetween" AlignItems="Center" Margin="20,0">
                                <Label 
                                    Text="{Binding Text}"
                                />

and what I do in my EditingPage VM to update Database await Service.AddNoteToDB(Text);


Solution

  • In Xamarin, you can use ObservableCollection instead of List for temporary storage of data.The xaml page will automatically refresh every time the value of the ObservableCollection is modified.

    For your logic needs, there are two workarounds.

    1. Modify the value inside the ObservableCollection after each modification to the database, so that the value of the xaml page will automatically refresh.

    2. Query the value from the database and change the value of the ObservableCollection every time you jump to the MainPage(override the OnAppearing method).