Asynchronously loading Blendable sample data into MVVM Light in the view model constructor

I have a Windows Phone 8.1 MVVM Light project and I try my best to keep it Blendable .

As I can see, I have several options. I can load different view models depending on whether ViewModelBase.IsInDesignModeStatic true in the ViewModelLocator constructor, or I can check ViewModelBase.IsInDesignModeStatic in the view model constructor and load the data accordingly.

If ViewModelBase.IsInDesignModeStatic true, I need to load data from a file. Here is my code:

 public async Task<ThingsSampleDataSource> GetSampleDataAsync() { if (_DeserializedThingsSampleDataSource == null) { var dataUri = new Uri(_SampleDataJSONFile); var file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); var jsonText = await FileIO.ReadTextAsync(file); _DeserializedThingsSampleDataSource = JsonConvert.DeserializeObject<ThingsSampleDataSource>(jsonText); } return _DeserializedThingsSampleDataSource; } 

When I call this method, I need to note the await call, and therefore the async call method. But constructors cannot be labeled async .

Or I can provide ContinueWith a continuation, rather than waiting for the return of asynchronous code. But Blend loads the page until ContinueWith completes.

Given that the data sample is loaded in the view model or in the constructor constructor and he needs to load data from a file, asynchronous activity, how to do it in MVVM Light so that sample data is available in Blend?

(NB other answers I found, like this one , do not use MVVM Light.)

+1
source share
1 answer

Load the data into the page load event using the command so that you can use the wait / asynchronous stuff. I do not know how this works with blend, since I do not use it much.

View:

 <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <i:InvokeCommandAction Command="{Binding PageLoadedCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> 

ViewModel:

 public RelayCommand PageLoadedCommand { get; private set; } public MyConstructor(IService serviceInjected) { PageLoadedCommand = new RelayCommand(async()=>await OnPageLoaded()); .... } private async Task OnPageLoaded() { if(ViewModelBase.IsInDesignModeStatic) { var data = await GetSampleDataAsync(); //Do something.. } } 
+1
source

Source: https://habr.com/ru/post/1210099/


All Articles