JadedEric
JadedEric

Reputation: 2083

Window 8 App Store long running process

I have a web service that will return around 360 entries from a database stored in Azure. In my ModelView I do an async call to retrieve the data, but the binding of the ModelView executes before the async call completes.

Is there a way to "wait" for the async to complete before I continue binding the ModelView to my view's DataContext, something similar to await?

// ModelView code

ServerSideModel.ProAmService.EntityServiceClient serviceClient = new ServerSideModel.ProAmService.EntityServiceClient();
serviceClient.GetPlayersPreviewCompleted += serviceClient_GetPlayersPreviewCompleted;
serviceClient.GetPlayersPreviewAsync(3);

Get's called in the constructor of the ModelView.

// View code

this.DataContext = _viewModel;

Called in the view's constructor.

Like I stated, the line this.DataContext = _viewModel get's called and the async function fires off without returning any data.

Upvotes: 1

Views: 196

Answers (1)

Jerry Nixon
Jerry Nixon

Reputation: 31823

You bet, it sounds to me like you may not know about ObservableCollection, a generic List that has XAML-aware events built-in. As you add or remove to this type of list, the XAML UI automatically reflects the changes. It's beautiful. Use it like this:

// pretend your service returns this
class MyItem { public string Name { get; set; } }

// this is a property in your view model, bind your gridview to it
public ObservableCollection<MyItem> Items { get; set; }

// call this to load, it will continue to populate the UI until it is done
async System.Threading.Tasks.Task LoadAsync()
{
    var _Results = await GetItemsAsync();
    foreach (var item in _Results.OrderBy(x => x.Name))
        this.Items.Add(item);
}

The rule of thumb for XAML development is that any type of list should be upgraded to an ObservableCollection so that it can bind easily and properly.

Read about ObservableCollections here: http://msdn.microsoft.com/en-us/library/ms668604.aspx Read more about XAML binding here: http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html

Upvotes: 3

Related Questions