Posted By

jiewmeng on 10/17/10


Tagged

MVVM


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Dialog Service for MVVM Apps


 / Published in: C#
 

In MVVM, where there should be little or no code behind with strong separation of concerns, one might wonder how to create dialogs. If you show a dialog using new SaveFileDialog(), when Unit Testing, a dialog will show, halting the unit test. With a service class such as this, one might provide a service implementing IDialogService that provides the ViewModel with the required information

  1. interface IDialogService
  2. {
  3. public string[] GetOpenFileDialog();
  4. public string GetSaveFileDialog();
  5. }
  6.  
  7. class DialogService : IDialogService
  8. {
  9. public string[] GetOpenFileDialog(string title, string filter)
  10. {
  11. var dialog = new OpenFileDialog();
  12. dialog.CheckFileExists = true;
  13. dialog.CheckPathExists = true;
  14. dialog.Multiselect = true;
  15. dialog.Title = title;
  16. dialog.Filter = filter;
  17. if ((bool)dialog.ShowDialog()) {
  18. return dialog.SafeFileNames;
  19. }
  20. return new string[0];
  21. }
  22.  
  23. public string GetSaveFileDialog(string title, string filter)
  24. {
  25. var dialog = new SaveFileDialog();
  26. dialog.Title = title;
  27. dialog.Filter = filter;
  28. if ((bool)dialog.ShowDialog()) {
  29. return dialog.SafeFileName;
  30. }
  31. return "";
  32. }
  33. }

Report this snippet  

You need to login to post a comment.