views:

94

answers:

3

I have a ViewModel where one of its functions is to talk to a service and get some data. However, if there is a problem, I would like a notify the user that the service could not run.

Currently what I am doing is firing an event which the view has subscribed to (my viewModel is created in the resources section of the view) and receiving the event in the view event handler I just do a Windows.Alert().

First, I am trying to reduce the amount of code in the code behind of the view and with the event firing, there must be a better way to do this?

Secondly, since my view knows about my view model (i.e. created in the resources section), I am sure this will cause problems in testing my view. Is this the correct way to do this?

JD.

+1  A: 

Yes, I don't think subscribing to an event in the VM from the View is a good idea. Almost better to put the alert in the VM, but that puts UI in the VM and makes it hard to test. There are a couple of other ways to handle this.

Bryant
Excellent links, thanks Bryant.
JD
+1  A: 

Best to use a service here. A service just provides some function through an interface.

public interface IDialogService {
    void ShowNotifictation(string message);
}

The ViewModel takes this service and uses it to display the notification. The implementation of this service is then specific to your solution, and can display the notification however you want.

Cameron MacFarland
Would a view implement the IDialogService?
JD
No, no. You just implement the service, and put it in your IOC container. The ViewModel should be able to retrieve it from there.
Cameron MacFarland
Sorry for the misunderstanding, ok, I have the service registered in my IoC container. The view model has it injected or can retrieve the service and then makes a call to ShowNotification(). Now what would the code look like for this method call (does it create a dialog and call show)?
JD
+1  A: 

Hi JD,

The implementation of such a service might look like this:

[Export(typeof(IMessageService))]
public class MessageService : IMessageService
{
    public void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }
...

It uses MEF as IoC Container. The service is registered via the Export attribute as IMessageService.

You might have a look at the WPF Application Framework (WAF) to see the full implementation and sample applications that are using this service.

Hope this helps.

jbe

jbe
Thanks for the code.
JD