Joshua G
Joshua G

Reputation: 2136

How to load data on page start in .net maui

How do you correctly start a data load in a page in a maui application? I see examples for how to bind existing data and how to start a call on pull down or button press but not how to start a call when the page first starts.

Upvotes: 3

Views: 6152

Answers (4)

Bruno T.
Bruno T.

Reputation: 1

The optimal approach to load data with an asynchronous task (executed on a separate thread) is to use the dispatcher to launch the async method. The following example demonstrates how to invoke the LoadAsync method (an async task) defined in the ViewModel within the OnAppearing event:

protected override void OnAppearing()
{
    base.OnAppearing();
    Dispatcher.DispatchAsync(ViewModel.LoadAsync);
}

This technique helps avoid the use of "async void" methods, ensuring better error handling and cleaner code execution.

Upvotes: 0

Michael Sullivan
Michael Sullivan

Reputation: 61

Use EventToCommandBehavior in Maui Community Toolkit.

<ContentPage xmlns:mct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" 
  ... other namespaces
  >

   <ContentPage.Behaviors>
    <mct:EventToCommandBehavior Command="{Binding AppearingCommand}" EventName="Appearing" />
   </ContentPage.Behaviors>
</ContentPage>

In your View Model

private bool _isInitialized = false;
[RelayCommand]
async Task AppearingAsync()
{
    if(_isInitialized) return;
    _isInitialized = true;
    await RefreshAsync();     
}

[RelayCommand]
async Task RefreshAsync()
{
// DoSomething        
}

Upvotes: 3

Julian
Julian

Reputation: 8924

You can make the OnAppearing() override async and await any loading calls:

protected override async void OnAppearing()
{
    base.OnAppearing();

    await someViewModelOrApi.LoadDataAsync();
}

Note that this will load the data every time the page appears again.

Alternatively, you can also use the Loaded event of the Page:

public MyPage()
{
    Loaded += OnPageLoaded;
}

private async void OnPageLoaded(object sender, EventArgs e)
{
    await someViewModelOrApi.LoadDataAsync();
}

In another answer I've also described how you can load data when a Page and its ViewModel are instantiated.

Upvotes: 4

Guangyu Bai - MSFT
Guangyu Bai - MSFT

Reputation: 4586

When overridden, OnAppearing() method allows application developers to customize behavior immediately prior to the Page becoming visible. You can write the method you want to use in OnAppearing().

protected override void OnAppearing()
{
    base.OnAppearing();
    // do your works
}

Upvotes: 2

Related Questions