I've been torn on this topic, as I see value either way. Now that I'm working on a ViewModel-First navigation library, I'm trying to decide where a user will typically (in a well-factored code base) hydrate their ViewModel.
by hydration, I'm not only referring to setting initial properties, but also calling async services and retrieving VM data.
OPTION 1: Hydrate in the page
public partial class FirstPage
{
FirstPageViewModel _viewModel;
IFooService _fooService;
public FirstPage(FirstPageViewModel viewModel, IFooService fooService)
{
_viewModel = viewModel;
_fooService = fooService;
InitializeComponent();
BindingContext = _viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
_viewModel.Person = await _fooService.GetTheCoolestPersonAsync();
// more long running tasks.
}
}
public class FirstPageViewModel
{
public Person Person {get;set;} // too lazy to write a bindable person.
}
OPTION 2: Hydrate in the ViewModel
public partial class FirstPage
{
FirstPageViewModel _viewModel;
public FirstPage(FirstPageViewModel viewModel)
{
InitializeComponent();
BindingContext = _viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await _viewModel.Init();
}
}
public class FirstPageViewModel
{
IFooService _fooService;
public FirstPageViewModel(IFooService fooService)
{
_fooService = fooService;
}
public async Task Init()
{
Person = await _fooService.GetTheCoolestPersonAsync();
// more long running tasks.
}
public Person Person {get;set;} // too lazy to write a bindable person.
}
OPTION 3: ?????????
For your preferred direction, what is your rational for leaning that way?