lookitskris
lookitskris

Reputation: 678

Returning Data from an Asynchronous Command in a WPF MVVM Application

I’m having a bit of difficulty getting this to work – and to be honest, I feel I may not be even doing this with the right approach.

In my View I have a Button and two list boxes.

What I want is to click the button and have the two list boxes populate with two separate lists of strings in an Asynchronous fashion.

In my ViewModel, I have two ObservableCollection properties and these are what the ListBox.ItemsSource properties are bound too. All good.

Now, I have an instance of AsyncDelegateCommand (outlined in this post - http://www.amazedsaint.com/2010/10/asynchronous-delegate-command-for-your.html#) which I have data bound to the Command property of the button.

In the DoSomething() method, I have just made a quick sample that constructs a list of random strings with a few sleep in-between to simulate some elapsed time.

How can I return this collection for use in the ViewModel? and then to take it a step further, How can I return multiple instances of this collection for multiple ListBoxes?

I hope this makes sense!

Kris

Upvotes: 1

Views: 402

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564681

Using the AsyncDelegateCommand you referenced, you would subscribe to the Command's Completed event, and add the results of your collection from event args Result to your ObservableCollection.

This will automatically happen in the correct synchronization context (since that command uses BackgroundWorker to function), which will allow your UI to update appropriately.

Upvotes: 1

Related Questions