Samstag, 15. Mai 2010

MVVM Pattern und user interaction (modal dialogs)

If you are using a MVVM pattern you have quickly the problem, that you need stuff like confirmation dialogs or message boxes to interact with the user. In my actual project (Silverlight 4 project with RIA Services hosted at the Windows Azure cloud) I use the approach to define a neutral interface IDialogProvider and a implementation with specific coding to show popup windows and return optional the result via callbacks. With this approach the view model is still independent from the presentation layer and testable with unit tests.

Architecture

image 

Implementation draft

The interface:
   1: public interface IDialogControlProvider
   2:     {
   3:         void DisplayErrorDialog(string errorMessage);
   4:         void DisplayInformationDialog(string informationMessage);
   5:         void DisplayConfirmationDialog(string title,string message,Action<int> callback);
   6:  
   7:     }
The implementation:
   1: public class DialogControlProvider:IDialogControlProvider
   2:     {
   3:  
   4:         #region IDialogProvider Members
   5:  
   6:         public void DisplayErrorDialog(string errorMessage)
   7:         {
   8:             var popup=new PopupErrorMessage("Fehlermeldung",errorMessage,true);
   9:             popup.Show();
  10:         }
  11:  
  12:         public void DisplayInformationDialog(string informationMessage)
  13:         {
  14:             var popup = new PopupErrorMessage("Information", informationMessage, false);
  15:             popup.Show();
  16:         }
  17:  
  18:         public void DisplayConfirmationDialog(string title,string message, Action<int> callback)
  19:         {
  20:             var result = SdxDialogResult.Yes;
  21:             callback(result);
  22:         }
Usage in the View model:

private IDialogControlProvider _dialogControl;

_dialogControl can be set via the contructor of the view model instance (in my case a view model locator class) or with a special initialize method.

   1: _dialogControl.DisplayConfirmationDialog("Frage", "Soll wirklich gespeichert werden?",
   2:     (dialogResult) =>
   3:     {
   4:         if (dialogResult == SdxDialogResult.Yes)
   5:         {
   6:             // do something
   7:         }
   8:     }

1 Kommentar: