Back to Devexpress

Standard DevExpress Services

windowsforms-114024-cross-platform-app-development-winforms-mvvm-design-time-support-control-based-services.md

latest41.0 KB
Original Source

Standard DevExpress Services

  • Jul 04, 2025
  • 27 minutes to read

DevExpress Services pass commands from a ViewModel to controls in a View. This allows you to modify the UI without separating application layers.

Available Services

Additional Information

How to Use Services

  1. Register a Service.
  • Local registration (the Service is available only in a View): call the mvvmContext1.RegisterService method and pass one of the Service’s Create methods as a parameter. The DevExpress MVVM Framework automatically registers most frequently used Services - see the note in the “Global Registration” section below.
  • Global registration (the Service available for the entire application): call the corresponding static MVVMContext.Register...Service method.
  1. Define a ViewModel property that returns an object of the related Service interface (for example, your property should be of the IDocumentManagerService type if you registered WindowedDocumentManagerService ).

  2. Use this property to access a Service and call Service methods to send commands to a View.

Example

csharp
//1. Global registration
MVVMContext.RegisterMessageBoxService();
//1. Local registration
mvvmContext1.RegisterService(CreateXtraMessageBoxService());

//2. POCO ViewModel property that returns a Service
protected virtual IMessageBoxService MessageBoxService {
    get { throw new System.NotImplementedException(); }
}

//3. Send a Service command to a View
public void SayHello() {
    MessageBoxService.Show("Hello!");
}
vb
'1. Global registration
MVVMContext.RegisterMessageBoxService()
'1. Local registration
mvvmContext1.RegisterService(CreateXtraMessageBoxService())

'2. POCO ViewModel property that returns a Service
protected virtual IMessageBoxService MessageBoxService
    Get
        Throw New System.NotImplementedException()
    End Get

'3. Send a Service command to a View
public void SayHello()
    MessageBoxService.Show("Hello!")

MessageBoxService

Allows you to display message boxes and flyouts.

Interface

IMessageBoxService

Managed Controls

Global Registration

csharp
MVVMContext.RegisterMessageBoxService();
MVVMContext.RegisterXtraMessageBoxService();
MVVMContext.RegisterFlyoutMessageBoxService();
vb
MVVMContext.RegisterMessageBoxService()
MVVMContext.RegisterXtraMessageBoxService()
MVVMContext.RegisterFlyoutMessageBoxService()

DevExpress MVVM Framework automatically calls the RegisterXtraMessageBoxService method.

Local Registration

csharp
mvvmContext1.RegisterService(
    //one of "Create" methods from the list below
);
vb
mvvmContext1.RegisterService(
    'one of "Create" methods from the list below
)

Create() Methods

  • Create(DefaultMessageBoxServiceType type) - uses the DefaultMessageBoxServiceType enumeration value to determine which Service type to create.
  • CreateMessageBoxService() - creates a Service that uses standard WinForms message boxes.
  • CreateXtraMessageBoxService() - creates a Service that uses DevExpress XtraMessageBox objects.
  • CreateFlyoutMessageBoxService() - creates a Service that uses FlyoutDialog objects.

All four methods have corresponding overloads with the second IWin32Window owner parameter. This parameter allows you to specify a View that owns this Service. If you pass null instead of the owner parameter, the Framework tries to locate an appropriate View that should be a Service owner. In most cases, the active window is used.

Public Service Members

  • ShowMessage - five extension methods that display message boxes.

  • MessageBoxFormStyle - allows you to access the Message Box form and modify its appearance settings. For instance, the code below illustrates how apply the bold font style to Message Box buttons.

Back to top


DialogService

Allows you to show dialogs.

Interface

IDialogService

Managed Controls

Global Registration

csharp
MVVMContext.RegisterXtraDialogService();
MVVMContext.RegisterFlyoutDialogService();
MVVMContext.RegisterRibbonDialogService();
vb
MVVMContext.RegisterXtraDialogService()
MVVMContext.RegisterFlyoutDialogService()
MVVMContext.RegisterRibbonDialogService()

The DevExpress MVVM Framework automatically calls the RegisterXtraDialogService method.

Local Registration

csharp
mvvmContext1.RegisterService(DialogService.CreateXtraDialogService(this));
mvvmContext1.RegisterService(DialogService.CreateFlyoutDialogService(this));
mvvmContext1.RegisterService(DialogService.CreateRibbonDialogService(this));
mvvmContext1.RegisterService(DialogService.Create(this, DefaultDialogServiceType.RibbonDialog));
vb
mvvmContext1.RegisterService(DialogService.CreateXtraDialogService(Me))
mvvmContext1.RegisterService(DialogService.CreateFlyoutDialogService(Me))
mvvmContext1.RegisterService(DialogService.CreateRibbonDialogService(Me))
mvvmContext1.RegisterService(DialogService.Create(Me, DefaultDialogServiceType.RibbonDialog))

Create() Methods

All ‘Create…’ methods for the DialogService require a View that owns this Service. If you pass null instead of a View, the Framework tries to locate an appropriate window (in most cases, an active window is used).

  • Create(IWin32Window owner, DefaultDialogServiceType type) - uses the DefaultDialogServiceType enumerator value to determine which Service type to create.

  • CreateXtraDialogService(IWin32Window owner) - creates a Service that shows skinnable DevExpress dialogs.

  • CreateFlyoutDialogService(IWin32Window owner) - creates a Service that displays FlyoutDialogs.

  • CreateRibbonDialogService(IWin32Window owner) - creates a Service that shows RibbonForms with embedded RibbonControls as dialogs. Dialog buttons appear as Ribbon items.

  • Create(IWin32Window owner, string title, Func<IDialogForm> factoryMethod) - allows you to register a Service that manages custom dialogs (objects that implement the IDialogForm interface).

  • DialogService Create(IWin32Window owner, string title, IDialogFormFactory factory) - accepts a factory class that creates custom dialogs.

Public Service Methods

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

  • DialogFormStyle - allows you to access the dialog and modify its appearance settings. For instance, the code below illustrates how apply the bold font style to Flyout Dialog buttons.

Back to top


Current Dialog Service

Allows you to manage currently visible dialogs.

Interface

DevExpress.Mvvm.ICurrentDialogService

Registration

A Service exists only when there is an active dialog - you cannot register a CurrentDialogService.

Create() Methods

None.

Public Service Methods

  • Close(), Close(MessageResult dialogResult) and Close (UICommand dialogResult) - closes a dialog with the given DialogResult. If the result is of UICommand type, a related UICommand is invoked. Note that you can use only one of the UICommands that were initially passed to the dialog service in the ShowDialog method.
  • WindowState - this property allows you to change a dialog’s window state (normal, minimized or maximized).

Back to top


CurrentWindowService

Similar to the CurrentDialogService, but allows you to manage current application windows (forms).

Interface

DevExpress.Mvvm.ICurrentWindowService

Global Registration

Not available.

Local Registration

csharp
mvvmContext1.RegisterService(CurrentWindowService.Create(this));
mvvmContext1.RegisterService(CurrentWindowService.Create(listBoxControl1));
vb
mvvmContext1.RegisterService(CurrentWindowService.Create(Me))
mvvmContext1.RegisterService(CurrentWindowService.Create(listBoxControl1))

Create() Methods

  • Create(Control container) - allows you to register a Service for any form that hosts a control assigned as the method’s parameter.
  • Create(Form currentForm) - registers a Service for this form.
  • Create(Func<Form> getCurrentForm) - registers a Service for any form the getCurrentForm method returns.

Public Service API

  • Activate(), Close(), Hide() and Show() - allow you to control the current window’s visibility.
  • WindowState - this property allows you to change a form’s window state (normal, minimized or maximized).

Back to top


Window Service

Allows you to show Views as independent windows (forms), and manage these windows from the ViewModel layer.

Interface

IWindowService

Managed Controls

Global Registration

csharp
MVVMContext.RegisterXtraFormService();
MVVMContext.RegisterFlyoutWindowService();
MVVMContext.RegisterRibbonWindowService();
vb
MVVMContext.RegisterXtraFormService()
MVVMContext.RegisterFlyoutWindowService()
MVVMContext.RegisterRibbonWindowService()

Local Registration

csharp
mvvmContext1.RegisterService(WindowService.Create(this, DefaultWindowServiceType.RibbonForm, "Window Title"));
mvvmContext1.RegisterService(WindowService.CreateXtraFormService(this, "Window Title"));
mvvmContext1.RegisterService(WindowService.CreateRibbonWindowService(this, "Window Title"));
mvvmContext1.RegisterService(WindowService.CreateFlyoutWindowService(this, "Window Title"));
vb
mvvmContext1.RegisterService(WindowService.Create(Me, DefaultWindowServiceType.RibbonForm, "Window Title"))
mvvmContext1.RegisterService(WindowService.CreateXtraFormService(Me, "Window Title"))
mvvmContext1.RegisterService(WindowService.CreateRibbonWindowService(Me, "Window Title"))
mvvmContext1.RegisterService(WindowService.CreateFlyoutWindowService(Me, "Window Title"))

Local Registration (Modal Windows)

If you want to display forms as modal dialogs, modify the Service’s ShowMode property before registration.

csharp
var service = WindowService.CreateXtraFormService(this, "Window Title");
service.ShowMode = WindowService.WindowShowMode.Modal;
mvvmContext1.RegisterService(service);
vb
Dim service = WindowService.CreateXtraFormService(Me, "Window Title")
service.ShowMode = WindowService.WindowShowMode.Modal
mvvmContext1.RegisterService(service)

Create() Methods

  • CreateXtraFormService(IWin32Window owner, string title = null) - creates a Service that manages XtraForms.
  • CreateRibbonWindowService(IWin32Window owner, string title = null) - creates a Service that manages Ribbon Forms.
  • CreateFlyoutWindowService(IWin32Window owner, string title = null) - creates a Service that manages Flyouts.
  • Create(IWin32Window owner, DefaultWindowServiceType type, string title = null) - creates a Service whose type depends on the type parameter.
  • Create(IWin32Window owner, string title = null, Func<IWindow> factoryMethod = null) - allows you to register a Service that manages custom forms (objects that implement the IWindow interface).
  • Create(IWin32Window owner, string title = null, IWindowFactory factory = null) - accepts a factory class that creates custom windows.

Public Service Methods

  • Show(object viewModel) - shows a View associated with this ViewModel.
  • Show(string documentType, object viewModel) - shows a specific View managed by the target ViewModel.
  • Show(string documentType, object parameter, object parentViewModel) - allows you to pass a specific parameter to a form.
  • Hide() and Activate() - allow you to minimize the form, or bring it to the front.
  • Close() - closes the managed window.

Back to top


DocumentManagerService

A local Service that provides methods to create and manage tabs inside MDI (multi-document interface) controls.

Interface

IDocumentManagerService

Managed Controls

Global Registration

Since the Service manages specific content providers, you cannot register this Service globally.

Local Registration

csharp
mvvmContext1.RegisterService(DocumentManagerService.Create(tabbedView1));
vb
mvvmContext1.RegisterService(DocumentManagerService.Create(tabbedView1))

Create() Methods

  • Create(IDocumentAdapterFactory factory) - creates a Service that controls a specific provider. The provider is a control or an object of the class, derived from the IDocumentAdapterFactory interface. The factory parameter accepts objects of the following types:

  • Create(Func<IDocumentAdapter> factoryMethod) - accepts a factoryMethod function that initializes a new factory object. This allows you to create custom factories (objects that implement the IDocumentAdapterFactory interface).

Public Service Methods

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

View Example: MVVM - Create documents and navigate between views (DocumentManagerService)

Back to top


WindowedDocumentManagerService

Allows you to add new forms that host custom content. If the Service is registered with the Create(IDocumentAdapterFactory factory) method, it adds new floating DocumentManager/XtraTabbedMdiManager panels instead of forms.

Interface

IDocumentManagerService

Managed Controls

Global Registration

csharp
MVVMContext.RegisterFormWindowedDocumentManagerService();
MVVMContext.RegisterXtraFormWindowedDocumentManagerService();
MVVMContext.RegisterRibbonFormWindowedDocumentManagerService();
vb
MVVMContext.RegisterFormWindowedDocumentManagerService()
MVVMContext.RegisterXtraFormWindowedDocumentManagerService()
MVVMContext.RegisterRibbonFormWindowedDocumentManagerService()

DevExpress MVVM Framework automatically calls the XtraFormWindowedDocumentManagerService method.

Local Registration

csharp
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));
vb
mvvmContext1.RegisterService(WindowedDocumentManagerService.Create(Me))
mvvmContext1.RegisterService(WindowedDocumentManagerService.CreateXtraFormService())
mvvmContext1.RegisterService(WindowedDocumentManagerService.CreateRibbbonFormService())
mvvmContext1.RegisterService(WindowedDocumentManagerService.CreateFlyoutFormService())
mvvmContext1.RegisterService(WindowedDocumentManagerService.Create(Me, DefaultWindowedDocumentManagerServiceType.RibbonForm))
mvvmContext1.RegisterService(WindowedDocumentManagerService.Create(tabbedView1))

Create() Methods

If you pass null instead of the owner paramter, the Framework tries to locate a View that should be a Service owner. In most cases, an active window is used.

  • 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 Service ( RegisterRibbonFormWindowedDocumentManagerService ), the local Service also shows Ribbon Forms. 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 Service type depends on the type parameter.

  • 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.

  • Create(IDocumentAdapterFactory factory) - an extension method that allows you to set a local content provider for the WindowedDocumentManagerService. A Service registered with this method adds child provider items as floating forms. For instance, the following code registers a Service associated with the DocumentManager’s TabbedView. When you call the CreateDocument method, the Service adds floating Documents to this TabbedView.

  • Create(Func<Form> factoryMethod, IWin32Window owner) - allows you to create custom factories (objects that implement the IDocumentAdapterFactory interface).

Public Service Methods

  • Documents - a property that provides access to the collection of items this Service manages.

  • ActiveDocument - gets or sets an active item.

  • CreateDocument - three extension methods that create a new item. Depending on the registration, the item is a separate form/XtraForm/RibbonForm or floating panel owned by a DocumentManager/XtraTabbedMdiManager.

Back to top


This service allows you to navigate from one View to another inside a NavigationFrame control, and open application Views as pages inside managed controls (for example, as TabbedView tabs).

Interface

INavigationService

Managed Controls

Global Registration

Not available.

Local Registration

csharp
mvvmContext1.RegisterService(NavigationService.Create(navigationFrame1));
vb
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 creates new items as the provider’s children.

Public Service Methods

The same commands as in the DocumentManagerService are available, plus the following navigation API:

  • BackNavigationMode - allows you to specify what module appears on-screen when a user presses the “Back” button: a previous or a root module.

  • GoBack, GoForward - navigates to the previously viewed module or discards this navigation.

  • CanGoBack, CanGoForward - returns whether it is possible to navigate in the given direction.

  • Navigate - navigates to the target View, whose name is passed to this method as a string parameter.

Back to top


DispatcherService

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

Interface

IDispatcherService

Managed Controls

None.

Global Registration

This service is already registered.

Local Registration

csharp
mvvmContext1.RegisterService(DispatcherService.Create());
vb
mvvmContext1.RegisterService(DispatcherService.Create())

Create() Methods

  • Create() - creates a new Service instance.

Public Service Methods

Back to top


Notification Service

Displays traditional Alert Windows and Windows Toast Notifications.

Interface

INotificationService

Managed Controls

Global Registration

Not available.

Local Registration

csharp
mvvmContext.RegisterService(NotificationService.Create(toastNotificationManager));
vb
mvvmContext.RegisterService(NotificationService.Create(toastNotificationManager))

Create() Methods

  • Create(INotificationProvider manager) - create a Service that uses the target manager to display notifications. Accepts ToastNotificationsManager and AlertControl class instances as a parameter.

Public Service Methods

  • CreatePredefinedNotification(string header, string body, string body2, object image = null) - creates a notification with an image, header text string, and two regular body text strings. Note that this method creates a notification but does not show it - to make it visible, call the ShowAsync methods. See the code snippet below for an example.

  • C#

  • VB.NET

csharp
protected INotificationService INotificationService {
    get { return this.GetService<INotificationService>(); }
}

public virtual INotification Notification {
    get;
    set;
}

public async void ShowNotification() {
    // Create a notification with the predefined template.
    Notification = INotificationService.CreatePredefinedNotification("Hello", "Have a nice day!", "Greeting");
    // Display the created notification asynchronously.
    try {
        await Notification.ShowAsync();
    }
    catch(AggregateException e) {
        // Handle errors.
        MessageBoxService.ShowMessage(e.InnerException.Message, e.Message);
    }
}

public void HideNotification() {
    // Hide the notification
    Notification.Hide();
}
vb
Protected ReadOnly Property INotificationService() As INotificationService
    Get
        Return Me.GetService(Of INotificationService)()
    End Get
End Property

Public Overridable Property Notification() As INotification

Public Async Sub ShowNotification()
    ' Create a notification with the predefined template.
    Notification = INotificationService.CreatePredefinedNotification("Hello", "Have a nice day!", "Greeting")
    ' Display the created notification asynchronously.
    Try
        Await Notification.ShowAsync()
    Catch ex As AggregateException
        ' Handle errors.
        MessageBoxService.ShowMessage(ex.InnerException.Message, ex.Message)
    End Try
End Sub

Public Sub HideNotification()
    ' Hide the notification.
    Notification.Hide()
End Sub

The ShowAsync method asynchronously raises an exception in a non-UI thread if the method fails to display a notification (for example, if a Windows OS setting disables toast notifications). This exception does not affect the UI thread. To handle these exceptions and respond to notification display failures, wrap calls of the ShowAsync method with the try..catch block.

  • CreateCustomNotification(object viewModel) - creates a notification with a ViewModel inside. 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, header text string, and two regular text strings for your notification. The code below illustrates an example.

Back to top


SplashScreen Service

This Service allows you to display Splash Screens and Wait Forms that indicate the application is busy.

Interface

ISplashScreenService

Managed Controls

Global Registration

This service is already registered.

Local Registration

csharp
mvvmContext.RegisterService(SplashScreenService.Create(splashScreenManager));
vb
mvvmContext.RegisterService(SplashScreenService.Create(splashScreenManager))

Create() Methods

  • Create(ISplashScreenServiceProvider serviceProvider) - creates a Service that manages the target Splash Screen Manager.

  • Create(ISplashScreenServiceProvider serviceProvider, DefaultBoolean throwExceptions) - creates a Service that manages the target Splash Screen Manager and can throw exceptions when an error occurs.

Public Service Methods

  • ShowSplashScreen(string documentType) - shows a Splash Screen or a wait form of the specific type. The ‘documentType’ parameter is the name of a ViewModel that is derived from the SplashScreen class and represents Splash Screen that needs to be shown. If you pass null as a parameter, a default Splash Screen designed by DevExpress is created.

  • HideSplashScreen() - hides the active Splash Screen or Wait Form.

  • SetSplashScreenProgress(double progress, double maxProgress) and SetSplashScreenState(object state) - methods that inject custom data into a currently visible Splash Screen or Wait Form. The ‘SetSplashScreenProgress’ method updates the Splash Screen progress bar. The ‘SetSplashScreenState’ sends data of any other type (for example, string data for Splash Screen labels).

Back to top


Open and Save File Dialog Services

These Services invoke dialogs that allow users to open and save files to a local storage.

Interfaces

IOpenFileDialogService, ISaveFileDialogService

Managed Controls

None.

Global Registration

Both Services are already registered.

Local Registration

csharp
mvvmContext1.RegisterService(OpenFileDialogService.Create());
mvvmContext1.RegisterService(OpenFileDialogService.Create(mySettings));
mvvmContext1.RegisterService(SaveFileDialogService.Create());
mvvmContext1.RegisterService(SaveFileDialogService.Create(mySettings));
vb
mvvmContext1.RegisterService(OpenFileDialogService.Create())
mvvmContext1.RegisterService(OpenFileDialogService.Create(mySettings))
mvvmContext1.RegisterService(SaveFileDialogService.Create())
mvvmContext1.RegisterService(SaveFileDialogService.Create(mySettings))

Create() Methods

  • Create() - creates a file dialog Service.

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

Public Service Methods

  • ShowDialog(Action<CancelEventArgs> fileOK, string directoryName) - shows the current dialog service. The fileOK callback is 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 for the saved file.

  • MultiSelect - a boolean property that specifies whether users are allowed to open multiple files simultaneously (OpenFileDialogService only).

  • OverwritePromt - a boolean property that specifies whether to display a confirmation message (SaveFileDialogService only) when you try to save a file with a name that already exists.

  • Title - a string value that specifies the dialog title. This and all the following properties are inherited from the base FileDialogService class.

  • DialogStyle - allows you to choose between regular WinForms and skinnable DevExpress dialogs.

  • 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.

  • File - returns a file this dialog opened (saved).

Back to top


Folder Browser Dialog Service

Interface

IFolderBrowserDialogService

Managed Controls

None.

Global Registration

This Service is already registered.

Local Registration

csharp
mvvmContext1.RegisterService(FolderBrowserDialogService.Create());
mvvmContext1.RegisterService(FolderBrowserDialogService.Create(options));
vb
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 ‘Public Service Methods’ section).

Public Service Methods

  • ShowDialog() - displays the Folder Browser Dialog.

  • ShowNewFolderButton - a boolean property that specifies whether users are allowed to create new folders in the current hierarchy.

  • StartPath - a string property that specifies the initially selected folder.

  • RootFolder - a property of the Environment.SpecialFolder type that limits the hierarchy to the specific folder (for example, ‘My Documents’ folder).

  • Description - a string property that allows you to specify a description for the dialog.

  • DialogStyle - allows you to choose between regular WinForms and DevExpress XtraFolderBrowser dialogs. The DevExpress dialog is available in either “Wide” or “Compact” style (see the XtraFolderBrowserDialog.DialogStyle property).

Back to top


How to Use Service Extension Methods

This section explains how to use the most common parameters of Service extension methods.

object viewModel

This parameter stores an instance of a child ViewModel that should be navigated to, opened in the dialog, hosted in a new DocumentManager’s document, etc. To create such instances, use the ViewModelSource.Create method.

csharp
//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);
    }
}
vb
'ViewModelA.vb
Public Class ViewModelA
    . . .
    Public Shared Function Create() As ViewModelA
        Return ViewModelSource.Create(Of ViewModelA)()
    End Function
End Class
'ViewModelB.vb
Public Class ViewModelB
    Private childViewModel As ViewModelA

    Public Sub New()
        childViewModel = ViewModelA.Create()
    End Sub

    Private ReadOnly Property DialogService() As IDialogService
        Get
            Return Me.GetService(Of IDialogService)()
        End Get
    End Property

    Public Sub ShowDialog()
        DialogService.ShowDialog(MessageButton.OK, "This dialog contains View A", "ViewA", childViewModel)
    End Sub
End Class

object parentViewModel

As an alternative to the SetParentViewModel extension method, this argument passes an instance of the parent ViewModel. Extension methods that use this argument often have the parameter argument as well.

object parameter

This argument pass specific objects to child ViewModels that implement the ISupportParameter interface. ViewModels that implement this interface have the Parameter property that recalculates this argument and passes it back to where the method was called from.

csharp
//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
vb
'child ViewModel
Public Class LoginViewModel
    Implements ISupportParameter
     . . .
    Public Property Parameter() As Object
        Get
            ' 3. Returns the new parameter value
        End Get
        Set(ByVal value As Object)
            ' 2. myParameter object received from the extension method.
        End Set
    End Property
End Class

'parent ViewModel
' 1. The extension method is called
DialogService.ShowDialog(MessageButton.OK, "This dialog passes the parameter to the child ViewModel", "LoginView", myParameter, Me)
' 4. myParameter object now has a new value, set within the child ViewModel

Method Variations

There are three possible method arguments: viewModel, parentViewModel, and parameter. However, there can be only two possible extension method combinations.

  1. viewModel: create a child ViewModel (including its parent and required parameters), and pass this instance to a View.
  2. Parameter + parentViewModel: arguments are injected into a View and passed to a child ViewModel created for this View.

In the latter case, use the Framework for data injection or call the following methods to postpone data injection:

csharp
//postpone all data injection
ViewModelInjectionPolicy.DenyViewModelInjection();

//postpone parameter injection
ViewModelInjectionPolicy.DenyImmediateParameterInjection();

//postpone parentViewModel injection
ViewModelInjectionPolicy.DenyImmediateParentViewModelInjection();
vb
'postpone all data injection
ViewModelInjectionPolicy.DenyViewModelInjection()

'postpone parameter injection
ViewModelInjectionPolicy.DenyImmediateParameterInjection()

'postpone parentViewModel injection
ViewModelInjectionPolicy.DenyImmediateParentViewModelInjection()

See Also

MVVM Services