Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I load my viewmodel and still get events?
    text
    copied!<p>I'm trying to implement MVVM and in the ViewModel I'm doing some async fetching of data. For that purpose I've tried to loading data in the constructor:</p> <pre><code>MyModel Model { get; set; } public MyViewModel() { Model = new MyModel(); Model.Foo = await LoadDataFromIsolatedStorage(); </code></pre> <p>But this isnt valid as you cant append async to the contructor. So I tried a public static load function:</p> <pre><code>MyModel Model { get; set; } public MyViewModel() { Model = new MyModel(); } async public static void Load() { Model.Foo = await LoadDataFromIsolatedStorage(); </code></pre> <p>But here WP8 complains that it <code>Cannot await void</code>. Because you would set up the ViewModel and bind it to the View in the code behind of the view. Boring. Lastly a fix is making the Load function return a ViewModel, so that you in the code behind of the view can do something like:</p> <pre><code>protected override void OnNavigatedTo(NavigationEventArgs e) { MyViewModel viewModel = await MyViewModel.Load(); </code></pre> <p>with the following code to load:</p> <pre><code>MyModel Model { get; set; } public MyViewModel() { Model = new MyModel(); } async public static Task&lt;MyViewModel&gt; Load() { MyViewModel viewModel = new MyViewModel(); viewModel.Model.Foo = await LoadDataFromIsolatedStorage(); return viewModel; </code></pre> <p>NOW, the problem at hand is that I have no control if the data loaded should force the application to navigate to another page. Lets say MyViewModel loads a variable from isolated storage, that should then make the app navigate to another page?</p> <p>I've set up eventlistener to MyViewModel to make the app navigate, but I cant do this when I initiate it.</p> <p>Does not work with events:</p> <pre><code>protected override void OnNavigatedTo(NavigationEventArgs e) { MyViewModel viewModel = await MyViewModel.Load(); viewModel.NavigationAction += viewmodel_NavigationAction; } void viewmodel_NavigationAction(sender, args) { NavigationService.Navigate(...) } </code></pre> <p>Would work but I "cannot await void":</p> <pre><code>async protected override void OnNavigatedTo(NavigationEventArgs e) { MyViewModel viewModel = new MyViewModel(); viewModel.NavigationAction += viewmodel_NavigationAction; await viewModel.Load(); // given the Load only is a async void and not Task&lt;T&gt; } void viewmodel_NavigationAction(sender, args) { NavigationService.Navigate(...) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload