Skip to main content
A newer version of this page is available. .

Control-based Services

  • 24 minutes to read

The ViewModel delegates certain View operations to Services. Most Services provided by DevExpress do not perform these operations, but instead send commands to a related control or component that is located within the View. This document enumerates all the available DevExpress Services, together with their related controls, and shows how to register and use them in your applications.

Interface

Services

Description

Related Control

IMessageBoxService

MessageBoxService

Shows a message box with specified parameters.

System.Windows.Forms.MessageBox

XtraMessageBox

FlyoutDialog

IDialogService

DialogService

Provides methods to show a dialog window.

XtraForm

FlyoutDialog

RibbonForm

IDocumentManagerService

DocumentManagerService

Local service that provides methods to create and manage documents as child objects of the related control

DocumentManager

Navigation Frame

XtraTabControl

XtraTabbedMdiManager

Dock Manager

TabFormControl

WindowedDocumentManagerService

Provides methods to create and manage documents as separate UI elements

System.Windows.Forms.Form

XtraForm

RibbonForm

FlyoutDialog

INavigationService

NavigationService

Allows you to navigate between Views.

DocumentManager

Navigation Frame

XtraTabControl

XtraTabbedMdiManager

Dock Manager

TabFormControl

IDispatcherService

DispatcherService

Allows you to perform actions in a ViewModel using the CompilerServices.

none

INotificationService

NotificationService

Provides methods to display both traditional and Windows Modern-styled notifications.

Toast Notification Manager

Alert Windows

ISplashScreenService

SplashScreenService

Allows you to display splash screens.

Splash Screen Manager

IOpenFileDialogService

OpenFileDialogService

Invokes a dialog that allows your end-users to open file(s).

none

ISaveFileDialogService

SaveFileDialogService

Invokes a dialog that allows your end-users to save file(s).

none

IFolderBrowserDialogService

FolderBrowserDialogService

Invokes a dialog that allows your end-users to browse, create, and select folders in the file system of the current machine.

none

Specifics for each particular service are described in separate sections below. The common workflow for all these services remains the same.

  1. The first step is make a decision about whether or not you require the service to be global or local. Refer to the Services topic if you have difficulties.
  2. Use appropriate registration depending on what you need. For global services, use static MVVMContext methods (the ‘Registration’ section). To register a local service, use the MVVMContext instance’s RegisterService method. In method parameters, use the selected service’s Create… method. All available methods are listed in the ‘Create Methods’ section. Note that depending on the used Create… method, the service’s behavior and look-and-feel of its objects at runtime can be completely different. For instance, the MessageBoxService is able to show different types of message boxes depending on the registration.

    Note

    Some services are already registered by default, so you do not need to register them manually. Service descriptions below contain more specific information on which service types are available without registration.

  3. Define a property within a ViewModel that returns an object of the related service interface (e.g., if you’ve registered the WindowedDocumentManagerService, your property must be of the IDocumentManagerService type).
  4. After that, you can use this property to access the required service and use its methods, enlisted in the ‘Usable Members’ section.

MessageBoxService

The MessageBoxService provides the messaging functionality for your application. Depending on how the service is registered, the look-and-feel of displayed messages differ. This service is registered by default (the XtraMessageBoxService type).

  • Registration

    • Global:

      
      MVVMContext.RegisterMessageBoxService();
      MVVMContext.RegisterXtraMessageBoxService();
      MVVMContext.RegisterFlyoutMessageBoxService();
      
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(
          //one of "Create" methods from the list below
      );
      
  • Create Methods

    • Create(DefaultMessageBoxServiceType type) - a more convenient version of the following three methods. Allows you to use the enumerator to quickly specify the service type that should be registered.
    • CreateMessageBoxService() - creates a service that uses standard window message boxes.
    • CreateXtraMessageBoxService() - creates a service that uses XtraMessageBox objects.
    • CreateFlyoutMessageBoxService() - creates a service that uses FlyoutDialog objects.
    • MessageBoxService.CreateMessageBoxService(IWin32Window owner),

      MessageBoxService.CreateXtraMessageBoxService(IWin32Window owner),

      MessageBoxService.CreateFlyoutMessageBoxService(IWin32Window owner),

      MessageBoxService.Create(DefaultMessageBoxServiceType type, IWin32Window owner) - similar to the previous methods, but in addition allow you to specify the service owner. Normally, you should pass the current View as an owner.

  • Usable Members

    • ShowMessage - five extension methods that display a message box with specific content.

DialogService

The DialogService allows you to interact with end-users using dialogs. Dialogs can be represented by different UI providers depending on the service’s registration. This service is registered by default (the XtraDialogService type).

  • Registration

    • Global:

      
      MVVMContext.RegisterXtraDialogService();
      MVVMContext.RegisterFlyoutDialogService();
      MVVMContext.RegisterRibbonDialogService();
      
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(DialogService.CreateXtraDialogService(this));
      mvvmContext1.RegisterService(DialogService.CreateFlyoutDialogService(this));
      mvvmContext1.RegisterService(DialogService.CreateRibbonDialogService(this));
      mvvmContext1.RegisterService(DialogService.Create(this, DefaultDialogServiceType.RibbonDialog));
      
  • Create Methods

    All ‘Create…’ methods for the DialogService require an owner as a parameter. Normally, you should pass the current view as the owner.

    • Create(IWin32Window owner, DefaultDialogServiceType type) - a more convenient version of the following three methods. Allows you to use an enumerator to quickly specify the service type that should be registered.
    • CreateXtraDialogService() - a service will use simple dialog windows that support Skins.
    • CreateFlyoutDialogService() - creates a service that displays FlyoutDialogs.
    • CreateRibbonDialogService() - dialogs will be represented as RibbonForms containing RibbonControls. Dialog buttons are shown as bar items within the Ribbon.
  • Usable Members

    • ShowDialog - six extension methods that display a dialog with specific appearance and content.

      
      public void FindCustomer() {
          if(DialogService.ShowDialog(MessageButton.OKCancel, "Find Customer", findDialogViewModel) == MessageResult.OK) {
              // do something
          }
      }
      

      These overloads also support replacing default dialog buttons with your custom UICommand objects. Note that for this approach you are required to set either the Id or Tag property of a custom command to a MessageResult or DialogResult value. Refer to the this example for more details.

      
      public void FindCustomer() {
          var findDialogViewModel = FindDialogViewModel.Create();
          findDialogViewModel.SetParentViewModel(this);
          var commands = new List<UICommand>
              {
                  // Button with custom command attached
                  new UICommand {
                      Id = "Find",
                      Caption = "Find",
                      Command = new DelegateCommand(() =>{
                           // . . . implement the Find command here 
                       }),
                      IsDefault = true,
                      IsCancel = false, 
                      Tag = DialogResult.OK
                  },
                  // standard button caption customization
                  new UICommand {
                       Caption = "Cancel Find",
                       Tag = DialogResult.Cancel
                  }
              };
          DialogService.ShowDialog(commands, "Find Customer", "FindDialogView", SelectedEntity, findDialogViewModel);
      }
      
    • DialogFormStyle - allows you to access the dialog and modify its appearance settings. For instance, the code below illustrates how to change the appearance settings for Flyout Dialog buttons.

      
      var service = DialogService.CreateFlyoutDialogService(this);
      service.DialogFormStyle = (form) =>
      {
          FlyoutDialog dialog = form as FlyoutDialog;
          dialog.Properties.AppearanceButtons.FontStyleDelta = FontStyle.Bold;
      };
      

DocumentManagerService

The DocumentManagerService provides functionality for content containers, such as DocumentManager, XtraTabbedMdiManager, Navigation Frame or Tabbed Form pages. Since the service is related to a specific content provider, it can be registered only locally (see the ‘Registration’ section below).

  • Registration

    • Global: none.
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(DocumentManagerService.Create(tabbedView1));
      
  • Create Methods

  • Usable Members

    • Documents - a property that provides access to the collection of items (documents, tabs, pages) owned by the related content provider.
    • ActiveDocument - gets or sets a currently active item.
    • CreateDocument - three extension methods that create a new item owned by this content provider. The type of the item created depends on the provider’s type. For traditional DocumentManager Views (TabbedView and NativeMdiView) and the XtraTabbedMdiManager control, the CreateDocument method will create an item, docked to the provider as a tab. In order to create a floating item, use the WindowedDocumentManagerService instead (see below).

WindowedDocumentManagerService

Like the DocumentManagerService, the WindowedDocumentManagerService interferes with content providers. The difference is that the WindowedDocumentManagerService works with global providers - Forms, XtraForms and RibbonForms. If you create a new document using the DocumentManagerService, it will be added to the related local content provider (DocumentManager, XtraTabbedMdiManager, NavigationFrame, XtraTabControl) as its child. The WindowedDocumentManagerService will instead create an independent object, hosted within a form of the target type (except for cases, when the service is registered using the Create(IDocumentAdapterFactory factory) method).

This service is registered by default (the XtraFormWindowedDocumentManagerService type).

  • Registration

    • Global:

      
      MVVMContext.RegisterFormWindowedDocumentManagerService();
      MVVMContext.RegisterXtraFormWindowedDocumentManagerService();
      MVVMContext.RegisterRibbonFormWindowedDocumentManagerService();
      
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(WindowedDocumentManagerService.Create(this));
      mvvmContext1.RegisterService(WindowedDocumentManagerService.CreateXtraFormService());
      mvvmContext1.RegisterService(WindowedDocumentManagerService.CreateRibbbonFormService());
      mvvmContext1.RegisterService(WindowedDocumentManagerService.CreateFlyoutFormService());
      mvvmContext1.RegisterService(WindowedDocumentManagerService.Create(this, DefaultWindowedDocumentManagerServiceType.RibbonForm));
      mvvmContext1.RegisterService(WindowedDocumentManagerService.Create(tabbedView1));
      
  • Create Methods

    • Create(IWin32Window owner) - creates the service of the default type with the specific owner. The default type is the type that is registered globally. For instance, if you have the globally registered ribbon form the service (RegisterRibbonFormWindowedDocumentManagerService), the ribbon form will be the default service type. If no global service was registered, the default type is XtraForm.
    • Create(IWin32Window owner, DefaultWindowedDocumentManagerServiceType type) - creates a local service with the target owner. The type of the service is specified by the type parameter.
    • Create(IDocumentAdapterFactory factory) - the extension method that allows you to set a local content provider for the WindowedDocumentManagerService. When created with this method, the service will create new items as the provider’s children, but will also make them initially floating.

      For instance, in the ‘Registration’ section, the following code is used.

      
      mvvmContext1.RegisterService(WindowedDocumentManagerService.Create(tabbedView1));
      

      This registers a WindowedDocumentManagerService, which will add new documents to the tabbedView1 as floating documents whenever the CreateDocument method is called.

      The following are the appropriate objects that deliver the IDocumentAdapterFactory interface and can be passed to this method as a parameter:

      XtraTabControl and NavigationFrame objects cannot be passed to this method, since their items are always docked as tabs and cannot be made floating.

    • CreateXtraFormService(IWin32Window owner) - registers a service that hosts its items within XtraForms.
    • CreateRibbbonFormService(IWin32Window owner) - registers a service that hosts its items within RibbonForms.
    • CreateFlyoutFormService(IWin32Window owner) - registers a service that hosts its items within Flyout Dialogs.
  • Usable Members

    • Documents - a property that provides access to the collection of items managed by this service.
    • ActiveDocument - gets or sets a currently active item.
    • CreateDocument - three extension methods that create a new item. Depending on the registration, the item will be either a separate form/XtraForm/RibbonForm, or a floating panel, owned by a DocumentManager/XtraTabbedMdiManager.

This service allows you to navigate from one View to another inside a NavigationFrame control. Additionally, can open Views as other related controls’ pages (e.g., as TabbedView tabs).

  • Registration

    • Global: none
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(NavigationService.Create(navigationFrame1));
      
  • Create Methods

    • Create(IDocumentAdapterFactory factory) - the extension method that allows you to set a local content provider for this service. When created with this method, the service will create new items as the provider’s children.
  • Usable Members

    Same as for the DocumentManagerService, plus the following API that supports navigation journal.

    • BackNavigationMode - allows you to specify whether pressing the “Back” button brings end-users to a previous or root screen.
    • GoBack, GoForward - navigates to the previously viewed module or discards this navigation.
    • CanGoBack, CanGoForward - returns whether or not the navigation is currently available.
    • Navigate - navigates to the target View, whose name is passed to this method as a string parameter.

DispatcherService

The DispatcherService performs a certain functionality in the View’s thread. This service is registered by default.

  • Registration

    • Global: none.
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(DispatcherService.Create());
      
  • Create Methods

    • Create() - creates a new instance of the DispatcherService.
  • Usable Members

    • BeginInvoke - performs required actions in the UI thread. For instance, the UpdateProgressOnUIThread method declared in the code sample below updates the progress bar. This method was used in the Asynchronous Commands section of the Commands topic.

      
      protected IDispatcherService DispatcherService {
          get { return this.GetService<IDispatcherService>(); }
      }
      
      void UpdateProgressOnUIThread(int progress) {
          DispatcherService.BeginInvoke(() =>
          {
              Progress = progress;
              this.RaisePropertyChanged(x => x.Progress);
          });
      }
      

Notification Service

Using this service, you can display notifications in either a traditional style (see Alert Windows) or Windows Modern-styled toast notifications (see Toast Notification Manager).

  • Registration

    • Global: none.
    • Local (see ‘Create Methods’):

      
      mvvmContext.RegisterService(NotificationService.Create(toastNotificationManager));
      
  • Create Methods

    • Create(INotificationProvider manager) - create a service that will use the target manager to display notifications. Accepts ToastNotificationsManager and AlertControl class instances as a parameter.
  • Usable Members

    • CreatePredefinedNotification(string header, string body, string body2, object image = null) - creates a notification with a predefined template. This template allows you to assign an image, a header text string and two regular body text strings. Note that this method only creates a notification; to make it visible you should manually call its Show or ShowAsync methods. The code snippet below illustrates an example.

      
      protected INotificationService INotificationService {
          get { return this.GetService<INotificationService>(); }
      }
      
      public virtual INotification Notification {
          get;
          set;
      }
      
      public void ShowNotification() {
          // Creating a notification with the predefined template
          Notification = INotificationService.CreatePredefinedNotification("Hello, buddy!", "Have a nice day!", "Greeting");
          // Displaying the created notification asynchronously
          Notification.ShowAsync();
      }
      
      public void HideNotification() {
          // Hiding the notification
          Notification.Hide();
      }
      
    • CreateCustomNotification(object viewModel) - creates a notification with content retrieved from a custom ViewModel. The viewModel parameter requires an instance of a class that implements the DevExpress.Utils.MVVM.Services.INotificationInfo interface. This interface exposes one image and three string properties that allow you to set an icon, a header text string and two regular text strings for your notification. The code below illustrates an example.

      
      public class HelloViewModelWithINotificationInfo : INotificationInfo {
          protected INotificationService INotificationService {
              get { return this.GetService<INotificationService>(); }
          }
      
          public virtual INotification Notification {
              get;
              set;
          }
      
          public void ShowNotification() {
              // Creating a custom notification
              Notification = INotificationService.CreateCustomNotification(this);
          }
      
          string INotificationInfo.Header {
              get { return "Hello, buddy!"; }
          }
      
          string INotificationInfo.Body {
              get { return "Have a nice day!"; }
          }
      
          string INotificationInfo.Body2 {
              get { return "Greeting"; }
          }
      
          System.Drawing.Image INotificationInfo.Image {
              get { return null; }
          }
      }
      

      Same as with the CreatePredefinedNotification method, the CreateCustomNotification creates a notification but does not automatically show it. You need to manually call the notifications’ ‘Show’ and ‘Hide’ method to make them appear on screen.

SplashScreen Service

This service allows you to display splash screens, indicating that the application is currently busy with a specific task. This service is registered by default.

  • Registration

    • Global:

      
      MVVMContext.RegisterSplashScreenService();
      
    • Local (see ‘Create Methods’):

      
      mvvmContext.RegisterService(SplashScreenService.Create(splashScreenManager));
      
  • Create Methods

    • Create(ISplashScreenServiceProvider serviceProvider) - creates a service that will use the target Splash Screen Manager.
    • Create(ISplashScreenServiceProvider serviceProvider, DefaultBoolean throwExceptions) - creates a service that will use the target Splash Screen Manager and, if specified, throw exceptions when an error occurs.
  • Usable Members

    • ShowSplashScreen(string documentType) - shows a splash screen of the specific type. The ‘documentType’ parameter is the name of a ViewModel that derives the SplashScreen class and represents a required splash screen. If you pass null as a parameter, a default splash screen designed by DevExpress will be created. You can use this splash screen for debugging purposes.
    • HideSplashScreen() - hides the currently visible splash screen.
    • SetSplashScreenProgress(double progress, double maxProgress) and SetSplashScreenState(object state) - methods that inject your custom data to the currently displayed splash screen. The ‘SetSplashScreenProgress’ method updates the splash screen’s progress bar value. The ‘SetSplashScreenState’ sends data of any other type (e.g., string data to set a custom text for splash screen’s labels). Calling these methods will only send your data, you have to receive and use data manually. The text below explains how to do that.

      Add a new splash screen using the Splash Screen Manager’s smart-tag. The code for your splash screen already contains the ‘Overrides’ region with an override for the SplashFormBase.ProcessCommand method (refer to this link to learn more about sending and receiving splash screen manager commands). You will use this method overload to receive data and apply it as needed.

      
      public partial class SplashScreen1 : SplashScreen {
           public SplashScreen1() {
               InitializeComponent();
           }
      
           #region Overrides
      
           public override void ProcessCommand(Enum cmd, object arg) {
               base.ProcessCommand(cmd, arg);
           }
      
           #endregion
      
       }
      

      The ‘SetSplashScreenProgress’ and ‘SetSplashScreenState’ methods can send required data directly. To do so, use simple objects (strings, numeric values, etc.) as these methods’ parameters. When you do so, the SplashFormBase.ProcessCommand method override will receive this data as the ‘arg’ parameter. The ‘cmd’ parameter will receive a DemoProgressSplashScreen.CommandId enumerator value. Check this parameter to determine which command was sent to your splash screen and use the ‘arg’ value accordingly.

      The code below illustrates an example. The ViewModel calls the SetSplashScreenState method to transmit the ‘Almost done… string for a splash screen label. The ‘SetSplashScreenProgress’ sends the current (80) and maximum (100) progress bar values.

      
      public class Form1ViewModel {
          protected ISplashScreenService SplashScreenService {
              get { return this.GetService<ISplashScreenService>(); }
          }
          public void Show() {
              SplashScreenService.ShowSplashScreen("SplashScreen1");
              SplashScreenService.SetSplashScreenState("Almost done..."); //label text
              SplashScreenService.SetSplashScreenProgress(80, 100); //progress bar values
          }
      }
      

      The sent data is always received as the ‘arg’ parameter, whereas the ‘cmd’ parameter differs depending on which service method was called. For the SetSplashScreenState method the ‘cmd’ parameter will return the CommandId.MVVMSetState value. The ‘SetSplashScreenProgress’ will transfer its two numeric values by calling the ProcessCommand method twice: first with the CommandId.SetMaxProgressValue value for the ‘cmd’ parameter, then with the CommandId.SetProgressValue value. This behavior allows you to identify what exactly is currently stored in the ‘arg’ parameter.

      
      public partial class SplashScreen1 : SplashScreen {
          public SplashScreen1() {
              InitializeComponent();
          }
      
          #region Overrides
          public override void ProcessCommand(Enum cmd, object arg) {
              base.ProcessCommand(cmd, arg);
              DemoProgressSplashScreen.CommandId command = (DemoProgressSplashScreen.CommandId)cmd;
              //received from the SetSplashScreenState method
              if(command == DemoProgressSplashScreen.CommandId.MVVMSetState)
                  labelControl2.Text = (string)arg;
              //two separate values received from the SetSplashScreenProgress method
              if(command == DemoProgressSplashScreen.CommandId.SetMaxProgressValue)
                  progressBarControl1.Properties.Maximum = (int)arg;
              if(command == DemoProgressSplashScreen.CommandId.SetProgressValue)
                  progressBarControl1.EditValue = (int)arg;
          }
          #endregion
      }
      

      The following image illustrates the result.

      WinForms MVVM - SplashScreen

      The example above works fine when you use the SetSplashScreenState method to customize the same splash screen element each time. Should you call this method to customize different elements, do not send values directly. Otherwise, the ProcessCommand method will receive the same cmd parameter value each time (CommandId.MVVMSetState) and it will be impossible to tell which element should use the received arg parameter value. For this scenario, use one of the following approaches instead.

      • Call the SetSplashScreenState method with a complex object as a parameter. This object must contain an enumerator value and the required data. You can use System.Tuple structures, System.Collections.Generic.KeyValuePair objects or simple object[] arrays as a parameter.
      • Call the SetSplashScreenState method that uses the DevExpress.Utils.MVVM.Services.SplashScreenServiceState object as a parameter. This object has two fields: Command and State. Same as before, use these fields to pass required data and a corresponding enumerator value.

      Both approaches are shown in the following code. First, declare a custom SplashScreenCommand enumerator.

      
      public enum SplashScreenCommand {
          StateLabelCommand,
          PercentLabelCommand,
          TrackBarCommand
      }
      

      These custom enumerator values are used to label different data, sent by the SetSplashScreenState method.

      
      public void Show() {
          SplashScreenService.ShowSplashScreen("SplashScreen1");
          //customizing the first label text
          SplashScreenService.SetSplashScreenState(new SplashScreenServiceState(SplashScreenCommand.StateLabelCommand, "Almost done..."));
          //customizing the second label text
          SplashScreenService.SetSplashScreenState(new SplashScreenServiceState(SplashScreenCommand.PercentLabelCommand, "80%"));
          //sending the current progress bar value
          object[] customArray = new object[] { SplashScreenCommand.ProgressBarCommand, 80 };
          SplashScreenService.SetSplashScreenState(customArray);
      }
      

      Now, since your values ship together with a corresponding enumerator value, you can easily determine what type of data is stored within your arg parameter and use it correctly.

      
      public override void ProcessCommand(Enum cmd, object arg) {
          base.ProcessCommand(cmd, arg);
          if(cmd.Equals(SplashScreenCommand.StateLabelCommand)) stateLabel.Text = (string)arg;
          if(cmd.Equals(SplashScreenCommand.PercentLabelCommand)) percentLabel.Text = (string)arg;
          if(cmd.Equals(SplashScreenCommand.ProgressBarCommand)) progressBarControl1.EditValue = (int)arg;
      }
      

      As a result, the same SetSplashScreenState method customizes a progress bar and two different labels.

      Winforms MVVM - Splash Screen 2

Open and Save File Dialog Services

These services invoke dialogs that allow your end-users to open and save files to a local storage. Both services are registered by default.

  • Registration

    • Global:

      
      MVVMContext.RegisterOpenFileDialogService();
      MVVMContext.RegisterSaveFileDialogService();
      
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(OpenFileDialogService.Create());
      mvvmContext1.RegisterService(OpenFileDialogService.Create(mySettings));
      mvvmContext1.RegisterService(SaveFileDialogService.Create());
      mvvmContext1.RegisterService(SaveFileDialogService.Create(mySettings));
      
  • Create Methods

    • Create() - creates a required file dialog service.
    • Create(SaveFileDialogServiceOptions dialogServiceOptions)/Create(OpenFileDialogServiceOptions dialogServiceOptions) - creates a required file dialog service with specified settings (see dialog properties, listed in the ‘Usable Members’ section).
  • Usable Members

    • ShowDialog(Action<CancelEventArgs> fileOK, string directoryName) - shows the current dialog service. The fileOK callback method will be executed if the file was successfully opened (saved). The optional directoryName parameter specifies the startup dialog folder. For the SaveFileDialogService, the third string fileName parameter is also available. This parameter specifies the default name under which the current file should be saved.
    • MultiSelect - a boolean property that specifies whether or not end-users are allowed to open multiple files at once (OpenFileDialogService only).
    • OverwritePromt - a boolean property that specifies whether or not attempting to save a file under a name that already belongs to an existing file should raise a confirmation message (SaveFileDialogService only).
    • Title - a string value that specifies the title of the dialog shown. This and all the following properties are inherited from the base FileDialogService.
    • DialogStyle - allows you to choose the dialog type:

    • Filter - a string value that specifies file extensions, supported by this dialog. This string should contain a description of the filter, followed by the vertical bar and the filter pattern. The following code illustrates an example.

      
      this.Filter = "JPEG Images|*.jpg;*.jpeg|PNG Images|*.png|RAW Image Data|*.raw";
      
    • File - a file opened (saved) by this dialog.

Folder Browser Dialog Service

Invokes a dialog that displays a folder hierarchy for the current machine. End-users can browse this hierarchy, create new folders and select existing folders (for instance, a folder where all files downloaded by your application will be stored). This service is registered by default.

  • Registration

    • Global:

      
      MVVMContext.RegisterFolderBrowserDialogService();
      
    • Local (see ‘Create Methods’):

      
      mvvmContext1.RegisterService(FolderBrowserDialogService.Create());
      mvvmContext1.RegisterService(FolderBrowserDialogService.Create(options));
      
  • Create Methods

    • Create() - creates a new instance of the folder browser dialog service.
    • Create(FolderBrowserDialogServiceOptions dialogServiceOptions) - creates a new instance of the folder browser dialog service with the specified settings (see dialog properties, listed in the ‘Usable Members’ section).
  • Usable Members

    • ShowDialog() - displays the folder browser dialog.
    • ShowNewFolderButton - a boolean property that specifies whether or not end-users are allowed to create new folders in the current hierarchy.
    • StartPath - a string property that specifies the start hierarchy path, displayed by the dialog.
    • RootFolder - a property of the Environment.SpecialFolder type that limits browsing folder hierarchy by a specific folder (e.g., ‘My Documents’ folder).
    • Description - a string property that allows you to set a description for the dialog.
    • DialogStyle - allows you to choose the dialog type and style:

Using the Extension Methods

All service extension methods use the same parameters, combined together in different ways. The list below explains how some of these parameters should be used.

  • object viewModel - an instance of a child ViewModel that should be navigated to, opened within the dialog, hosted in a new DocumentManager’s document, etc. It is important to create such instances not using the new keyword, but by calling the Create method of the ViewModelSource class.

    
    //ViewModelA.cs
    public class ViewModelA {
        . . .
        public static ViewModelA Create() {
            return ViewModelSource.Create<ViewModelA>();
        }
    }
    
    //ViewModelB.cs
    public class ViewModelB {
        ViewModelA childViewModel;
    
        public ViewModelB() {
            childViewModel = ViewModelA.Create();
        }
    
        IDialogService DialogService {
            get { return this.GetService<IDialogService>(); }
        }
    
        public void ShowDialog() {
            DialogService.ShowDialog(MessageButton.OK, "This dialog contains View A", "ViewA", childViewModel);
        }
    }
    
  • object parentViewModel - used to pass an instance of the parent ViewModel. Such extension methods often use the parameter argument as well. The parent ViewModel can also be set using the SetParentViewModel extension method.
  • object parameter - the argument used to pass specific objects to the child ViewModel. To do so, you need to implement the ISupportParameter interface for your child ViewModel. After that, your child ViewModel will be able to implement the Parameter property that recalculates this parameter and passes it back to where the method was called from. This mechanic is shown in the following code.

    
    //child ViewModel
    public class LoginViewModel: ISupportParameter {
         . . .
        public object Parameter {
            get {
                // 3. Returns the new parameter value
            }
            set {
                // 2. myParameter object received from the extension method.
            }
        }
    }
    
    //parent ViewModel
    // 1. The extension method is called
    DialogService.ShowDialog(MessageButton.OK, "This dialog passes the parameter to the child ViewModel", "LoginView", myParameter, this);
    // 4. myParameter object now has a new value, set within the child ViewModel
    

    Note that in the code above the last ShowDialog method argument receives this as a parent ViewModel. In fact, all methods that use the parameter argument, always use the parentViewModel as well, but never the viewModel argument. This is reasonable since passing the child ViewModel instance as an argument is another way to pass parameters: either you use a method with a parameter to recalculate it within the child ViewModel and use the latter with an updated value, or you pass the already initialized child ViewModel that will be injected into your dialog/message box/document, etc.

See Also