1
votes

I am starting off writing an app for WP7 that involves retrieving data via an HTTPWebRequest, I am trying to find the best way to get the data back to the ViewModel once the async request has returned with the data.

The Model and ViewModel are split into seperate projects in their own namespaces, so am not sure if the MVVM-Light can work in this way. Or should I just use a lightweight IoC implementation and delegates/events to call back to the ViewModel once the call in the Model has returned?

2

2 Answers

1
votes

Try this out for size: http://amazedsaint.blogspot.com/2010/10/asynchronous-delegate-command-for-your.html. Great for testing as well, as none of your methods need to be Asynchronous, you just execute your Async Command.

I edited it slightly to extend the DelegateCommand so I could call RaiseCanExecuteChanged() method, as below:

public class AsyncDelegateCommand : DelegateCommand, ICommand
{

    BackgroundWorker _worker = new BackgroundWorker();
    Func<bool> _canExecute;

    /// <summary>
    /// The constructor
    /// </summary>
    /// <param name="action">The action to be executed</param>
    /// <param name="canExecute">Will be used to determine if the action can be executed</param>
    /// <param name="completed">Will be invoked when the action is completed</param>
    /// <param name="error">Will be invoked if the action throws an error</param>
    public AsyncDelegateCommand(Action action,
                                Func<bool> canExecute = null,
                                Action<object> completed = null,
                                Action<Exception> error = null
                                ) : base(action, canExecute)
    {
    ...
    }
}

Hope that's of help.

0
votes

Are you sure you're making the request in the right place? Typically the Model contains simply the data that you want to store/transfer and the View Model would handle transforming that Model's properties so that a View can display (or edit) that Model. I would imagine that Model objects are what you're going to get back from the HttpWebRequest, and so you may want to consider using a Service class to handle retrieving the data, though that may be overkill for your application.

Either way, I'd highly reccomend that you handle the request and the parsing of the response in the same place; otherwise you are spreading the logic across multiple places, which is just going to get confusing and hard to maintain.

If you need some help understanding MVVM, here are a number of resources that you may find helpf