windowsforms-114024-cross-platform-app-development-winforms-mvvm-design-time-support-control-based-services.md
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
- Local registration (the Service is available only in a View): call the
mvvmContext1.RegisterServicemethod and pass one of the Service’sCreatemethods 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...Servicemethod.
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 ).
Use this property to access a Service and call Service methods to send commands to a View.
Example
//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!");
}
'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!")
Allows you to display message boxes and flyouts.
MVVMContext.RegisterMessageBoxService();
MVVMContext.RegisterXtraMessageBoxService();
MVVMContext.RegisterFlyoutMessageBoxService();
MVVMContext.RegisterMessageBoxService()
MVVMContext.RegisterXtraMessageBoxService()
MVVMContext.RegisterFlyoutMessageBoxService()
DevExpress MVVM Framework automatically calls the RegisterXtraMessageBoxService method.
mvvmContext1.RegisterService(
//one of "Create" methods from the list below
);
mvvmContext1.RegisterService(
'one of "Create" methods from the list below
)
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.
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.
Allows you to show dialogs.
MVVMContext.RegisterXtraDialogService();
MVVMContext.RegisterFlyoutDialogService();
MVVMContext.RegisterRibbonDialogService();
MVVMContext.RegisterXtraDialogService()
MVVMContext.RegisterFlyoutDialogService()
MVVMContext.RegisterRibbonDialogService()
The DevExpress MVVM Framework automatically calls the RegisterXtraDialogService method.
mvvmContext1.RegisterService(DialogService.CreateXtraDialogService(this));
mvvmContext1.RegisterService(DialogService.CreateFlyoutDialogService(this));
mvvmContext1.RegisterService(DialogService.CreateRibbonDialogService(this));
mvvmContext1.RegisterService(DialogService.Create(this, DefaultDialogServiceType.RibbonDialog));
mvvmContext1.RegisterService(DialogService.CreateXtraDialogService(Me))
mvvmContext1.RegisterService(DialogService.CreateFlyoutDialogService(Me))
mvvmContext1.RegisterService(DialogService.CreateRibbonDialogService(Me))
mvvmContext1.RegisterService(DialogService.Create(Me, DefaultDialogServiceType.RibbonDialog))
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.
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.
Allows you to manage currently visible dialogs.
DevExpress.Mvvm.ICurrentDialogService
A Service exists only when there is an active dialog - you cannot register a CurrentDialogService.
None.
ShowDialog method.Similar to the CurrentDialogService, but allows you to manage current application windows (forms).
DevExpress.Mvvm.ICurrentWindowService
Not available.
mvvmContext1.RegisterService(CurrentWindowService.Create(this));
mvvmContext1.RegisterService(CurrentWindowService.Create(listBoxControl1));
mvvmContext1.RegisterService(CurrentWindowService.Create(Me))
mvvmContext1.RegisterService(CurrentWindowService.Create(listBoxControl1))
Allows you to show Views as independent windows (forms), and manage these windows from the ViewModel layer.
MVVMContext.RegisterXtraFormService();
MVVMContext.RegisterFlyoutWindowService();
MVVMContext.RegisterRibbonWindowService();
MVVMContext.RegisterXtraFormService()
MVVMContext.RegisterFlyoutWindowService()
MVVMContext.RegisterRibbonWindowService()
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"));
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"))
If you want to display forms as modal dialogs, modify the Service’s ShowMode property before registration.
var service = WindowService.CreateXtraFormService(this, "Window Title");
service.ShowMode = WindowService.WindowShowMode.Modal;
mvvmContext1.RegisterService(service);
Dim service = WindowService.CreateXtraFormService(Me, "Window Title")
service.ShowMode = WindowService.WindowShowMode.Modal
mvvmContext1.RegisterService(service)
IWindow interface).A local Service that provides methods to create and manage tabs inside MDI (multi-document interface) controls.
Since the Service manages specific content providers, you cannot register this Service globally.
mvvmContext1.RegisterService(DocumentManagerService.Create(tabbedView1));
mvvmContext1.RegisterService(DocumentManagerService.Create(tabbedView1))
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).
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)
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.
MVVMContext.RegisterFormWindowedDocumentManagerService();
MVVMContext.RegisterXtraFormWindowedDocumentManagerService();
MVVMContext.RegisterRibbonFormWindowedDocumentManagerService();
MVVMContext.RegisterFormWindowedDocumentManagerService()
MVVMContext.RegisterXtraFormWindowedDocumentManagerService()
MVVMContext.RegisterRibbonFormWindowedDocumentManagerService()
DevExpress MVVM Framework automatically calls the XtraFormWindowedDocumentManagerService method.
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));
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))
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).
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.
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).
Not available.
mvvmContext1.RegisterService(NavigationService.Create(navigationFrame1));
mvvmContext1.RegisterService(NavigationService.Create(navigationFrame1))
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.
Allows you to perform actions in a ViewModel using the Dispatcher.
None.
This service is already registered.
mvvmContext1.RegisterService(DispatcherService.Create());
mvvmContext1.RegisterService(DispatcherService.Create())
BeginInvoke - Executes the specified delegate asynchronously. See the Asynchronous Commands section of the Commands topic and the Async Command with Cancellation demo module for the examples.Displays traditional Alert Windows and Windows Toast Notifications.
Not available.
mvvmContext.RegisterService(NotificationService.Create(toastNotificationManager));
mvvmContext.RegisterService(NotificationService.Create(toastNotificationManager))
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.
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();
}
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.This Service allows you to display Splash Screens and Wait Forms that indicate the application is busy.
This service is already registered.
mvvmContext.RegisterService(SplashScreenService.Create(splashScreenManager));
mvvmContext.RegisterService(SplashScreenService.Create(splashScreenManager))
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.
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).
These Services invoke dialogs that allow users to open and save files to a local storage.
IOpenFileDialogService, ISaveFileDialogService
None.
Both Services are already registered.
mvvmContext1.RegisterService(OpenFileDialogService.Create());
mvvmContext1.RegisterService(OpenFileDialogService.Create(mySettings));
mvvmContext1.RegisterService(SaveFileDialogService.Create());
mvvmContext1.RegisterService(SaveFileDialogService.Create(mySettings));
mvvmContext1.RegisterService(OpenFileDialogService.Create())
mvvmContext1.RegisterService(OpenFileDialogService.Create(mySettings))
mvvmContext1.RegisterService(SaveFileDialogService.Create())
mvvmContext1.RegisterService(SaveFileDialogService.Create(mySettings))
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).
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).
None.
This Service is already registered.
mvvmContext1.RegisterService(FolderBrowserDialogService.Create());
mvvmContext1.RegisterService(FolderBrowserDialogService.Create(options));
mvvmContext1.RegisterService(FolderBrowserDialogService.Create())
mvvmContext1.RegisterService(FolderBrowserDialogService.Create(options))
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).
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).
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.
//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);
}
}
'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.
//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
'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.
In the latter case, use the Framework for data injection or call the following methods to postpone data injection:
//postpone all data injection
ViewModelInjectionPolicy.DenyViewModelInjection();
//postpone parameter injection
ViewModelInjectionPolicy.DenyImmediateParameterInjection();
//postpone parentViewModel injection
ViewModelInjectionPolicy.DenyImmediateParentViewModelInjection();
'postpone all data injection
ViewModelInjectionPolicy.DenyViewModelInjection()
'postpone parameter injection
ViewModelInjectionPolicy.DenyImmediateParameterInjection()
'postpone parentViewModel injection
ViewModelInjectionPolicy.DenyImmediateParentViewModelInjection()
See Also