Reputation: 557
I have a async rest service that create a List<> when page is loaded through OnAppearing event.
protected async override void OnAppearing()
{
base.OnAppearing();
RestService restService = new RestService();
List<Example> exampleList = await restService.GetExample();
}
What is the best practice to populate XAML ListView with exampleList when async operation is ready using MVVM pattern?
Upvotes: 0
Views: 1166
Reputation: 1123
I personally provide a base ContentPage implementation and in there point events to an interface that is implemented in the view model. E.G.
public interface IPageAppearingEvent
{
void OnAppearing();
}
public class BasePage : ContentPage
{
protected override void OnBindingContextChanged ()
{
base.OnBindingContextChanged ();
var onAppearingLifeCycleEvents = BindingContext as IPageAppearingEvent;
if (onAppearingLifeCycleEvents != null) {
var lifecycleHandler = onAppearingLifeCycleEvents;
base.Appearing += (object sender, EventArgs e) => lifecycleHandler.OnAppearing ();
}
}
}
public class ViewModel : IPageAppearingEvent
{
public void OnAppearing()
{
//Do whatever you like in here
}
}
As long as you ensure your views are subclasses of the BasePage then you are good to go.
Upvotes: 3