Reputation: 549
I have a windows phone application built using the MVVM pattern and I have pages that have to load data. I know this practice is bad but I used an async void LoadData()
called in the constructor to load data. Are there any better ways to achive this?
Thanks in advance
public class SomeViewModel: BaseViewModel
{
public SomeViewModel()
{
LoadData();
}
public async void LoadData()
{
//load data, ex. add items to list
}
private RelayCommand _refreshCommand;
/// <summary>
/// Gets the RefreshCommand.
/// </summary>
public RelayCommand RefreshCommand
{
get
{
return _refreshCommand
?? (_refreshCommand = new RelayCommand(() => LoadData()));
}
}
}
Upvotes: 0
Views: 277
Reputation: 110
Who's responsible for create view model is Ioc in Locator, so putting your LoadData method on constructor you will not have control.
My advice: Does not load data in Vm constructor. Do like this:
public class SomeViewModel: BaseViewModel
{
public IMessenger Messenger { get { return base.MessengerInstance; } }
public SomeViewModel()
{
Initialize();
}
public void Initialize()
{
RegisterMessengers();
}
public void RegisterMessengers()
{
Messenger.Register<string>(
this, "TokenRefresh", u => LoadData(u));
}
public async void LoadData(string u)
{
//load data, ex. add items to list
}
private RelayCommand _refreshCommand;
/// <summary>
/// Gets the RefreshCommand.
/// </summary>
public RelayCommand RefreshCommand
{
get
{
return _refreshCommand
?? (_refreshCommand = new RelayCommand(() => LoadData()));
}
}
}
And you call from another view model like that:
_navigationService.Navigate(typeof(YourView));
Messenger.Send("", "TokenRefresh");
Upvotes: 1