Standard DevExpress Services
- 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.
- MessageBoxService
- DialogService
- Current Dialog Service
- CurrentWindowService
- Window Service
- DocumentManagerService
- WindowedDocumentManagerService
- NavigationService
- DispatcherService
- Notification Service
- SplashScreen Service
- Open and Save File Dialog Services
- Folder Browser Dialog Service
Additional Information
How to Use Services
- Register a Service.
- Local registration (the Service is available only in a View): call the
mvvmContext1.RegisterService
method and pass one of the Service’sCreate
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.
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!");
}
MessageBoxService
Allows you to display message boxes and flyouts.
Interface
Managed Controls
- System.Windows.Forms.MessageBox
- XtraMessageBox
- FlyoutDialog
Global Registration
MVVMContext.RegisterMessageBoxService();
MVVMContext.RegisterXtraMessageBoxService();
MVVMContext.RegisterFlyoutMessageBoxService();
DevExpress MVVM Framework automatically calls the RegisterXtraMessageBoxService
method.
Local Registration
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.
DialogService
Allows you to show dialogs.
Interface
Managed Controls
Global Registration
MVVMContext.RegisterXtraDialogService();
MVVMContext.RegisterFlyoutDialogService();
MVVMContext.RegisterRibbonDialogService();
The DevExpress MVVM Framework automatically calls the RegisterXtraDialogService
method.
Local Registration
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 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.public void FindCustomer() { if(DialogService.ShowDialog(MessageButton.OKCancel, "Find Customer", findDialogViewModel) == MessageResult.OK) { // do something } }
These overloads allow you to replace default dialog buttons with custom UICommand objects. To do this, use the Id or Tag property of a custom command as a MessageResult or DialogResult value.
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 apply the bold font style to Flyout Dialog buttons.
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).
CurrentWindowService
Similar to the CurrentDialogService, but allows you to manage current application windows (forms).
Interface
DevExpress.Mvvm.ICurrentWindowService
Global Registration
Not available.
Local Registration
mvvmContext1.RegisterService(CurrentWindowService.Create(this));
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).
Window Service
Allows you to show Views as independent windows (forms), and manage these windows from the ViewModel layer.
Interface
Managed Controls
Global Registration
MVVMContext.RegisterXtraFormService();
MVVMContext.RegisterFlyoutWindowService();
MVVMContext.RegisterRibbonWindowService();
Local Registration
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"));
Local Registration (Modal Windows)
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);
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 IWindowFactory 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.
DocumentManagerService
A local Service that provides methods to create and manage tabs inside MDI (multi-document interface) controls.
Interface
Managed Controls
Global Registration
Since the Service manages specific content providers, you cannot register this Service globally.
Local Registration
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 (see below).
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
Managed Controls
- System.Windows.Forms.Form
- XtraForm
- RibbonForm
- FlyoutDialog
Global Registration
MVVMContext.RegisterFormWindowedDocumentManagerService();
MVVMContext.RegisterXtraFormWindowedDocumentManagerService();
MVVMContext.RegisterRibbonFormWindowedDocumentManagerService();
DevExpress MVVM Framework automatically calls the XtraFormWindowedDocumentManagerService
method.
Local Registration
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
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.The following objects implement the IDocumentAdapterFactory interface and can be passed to this method as a parameter:
- TabbedView and NativeMdiView views for the DocumentManager component;
- XtraTabbedMdiManager.
XtraTabControl and NavigationFrame child items are always docked. You cannot use these controls as a factory parameter.
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.
NavigationService
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
Managed Controls
Global Registration
Not available.
Local Registration
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.
DispatcherService
Allows you to perform actions in a ViewModel using the Dispatcher.
Interface
Managed Controls
None.
Global Registration
This service is already registered.
Local Registration
Create() Methods
- Create() - creates a new Service instance.
Public Service Methods
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.
Notification Service
Displays traditional Alert Windows and Windows Toast Notifications.
Interface
Managed Controls
Global Registration
Not available.
Local Registration
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 theShowAsync
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();
}
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.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; } } }
The CreateCustomNotification method creates a notification but does not show it. To show notifications, call the notifications’ ‘Show’ and ‘Hide’ methods.
SplashScreen Service
This Service allows you to display Splash Screens and Wait Forms that indicate the application is busy.
Interface
Managed Controls
Global Registration
This service is already registered.
Local Registration
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.To display a Fluent Splash Screen or an Overlay Form, pass a corresponding string ID to the
ShowSplashScreen
method.Overlay Form:
//ViewModel public class OverlayViewModel { protected ISplashScreenService SplashScreenService { get { return this.GetService<ISplashScreenService>(); } } public async System.Threading.Tasks.Task Wait() { SplashScreenService.ShowSplashScreen("#Overlay#"); //do something await System.Threading.Tasks.Task.Delay(2500); SplashScreenService.HideSplashScreen(); } } //View mvvmContext.ViewModelType = typeof(OverlayViewModel); mvvmContext.RegisterService(SplashScreenService.Create(splashScreenManager)); var fluent = mvvmContext.OfType<OverlayViewModel>(); fluent.BindCommand(showButton, x => x.Wait);
Fluent Splash Screen:
//ViewModel public class FluentSplashScreenViewModel { protected ISplashScreenService SplashScreenService { get { return this.GetService<ISplashScreenService>(); } } public void Show() { SplashScreenService.ShowSplashScreen("#FluentSplashScreen#"); } public void Hide() { System.Threading.Thread.Sleep(1000); SplashScreenService.HideSplashScreen(); } } //View mvvmContext.RegisterService(SplashScreenService.Create(splashScreenManager)); var fluent = mvvmContext.OfType<FluentSplashScreenViewModel>(); fluent.BindCommand(showButton, x => x.Show); fluent.BindCommand(hideButton, x => x.Hide);
HideSplashScreen()
- hides the active Splash Screen or Wait Form.SetSplashScreenProgress(double progress, double maxProgress)
andSetSplashScreenState(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).Splash Screens
Splash Screens can utilize both methods. To receive and use injected data, add a new Splash Screen with the Splash Screen Manager’s smart-tag menu. The code for your Splash Screen contains the ‘Overrides’ region: override its SplashFormBase.ProcessCommand method to parse data (see the method description for a complete sample).
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 also send data to Splash Screens and Wait Forms. To do so, use simple objects (strings, numeric values, etc.) as method parameters. When you do so, the SplashFormBase.ProcessCommand method receives these simple objects as the ‘arg’ parameter, and a DemoProgressSplashScreen.CommandId enumerator value as the ‘cmd’ parameter. Check the ‘cmd’ parameter to determine which command was sent to your Splash Screen and use the ‘arg’ value accordingly.
The ViewModel code below 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 SetSplashScreenState method calls the
ProcessCommand
override with the CommandId.MVVMSetState value for the cmd parameter. The SetSplashScreenProgress method calls theProcessCommand
override twice: first, the cmd parameter returns CommandId.SetMaxProgressValue; second, the cmd parameter returns CommandId.SetProgressValue. Read these parameter values to apply data from 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.
Use the example above when you update one Splash Screen element. Othewise, since the SetSplashScreenState method always returns CommandId.MVVMSetState as the cmd parameter, it is impossible to tell where the arg data should go to. For this scenario, use one of the following approaches instead.
- Call the SetSplashScreenState method with a complex object as a parameter. This object should contain an enumerator value and the required data. You can use
System.Tuple
structures,System.Collections.Generic.KeyValuePair
objects, orobject[]
arrays as a parameter.
- Call the SetSplashScreenState method that uses the
DevExpress.Utils.MVVM.Services.SplashScreenServiceState
object as a parameter. This object has the Command and State fields. Use these fields to pass required data and a corresponding enumerator value.
These approaches are shown in the following code. First, declare a custom SplashScreenCommand enumerator.
public enum SplashScreenCommand { StateLabelCommand, PercentLabelCommand, ProgressBarCommand }
These custom enumerator values label different data types from 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); }
Since your data now ships with a corresponding enumerator value, you can determine what data is stored in the 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; }
The figure below illustrates a splash screen with a progress bar and two labels. These three elements are updated with the SetSplashScreenState method.
Wait Forms
To display a Wait Form, use same
ShowSplashScreen
andSetSplashScreenState
methods. Wait Forms have two standard text blocks - caption and description. For that reason, theSetSplashScreenState
should pass a two-string array parsed inside the Wait Form’sProcessCommand
method.public class MyWaitForm : DevExpress.XtraWaitForm.DemoWaitForm { public override void ProcessCommand(Enum cmd, object arg) { string[] args = arg as string[]; SetCaption(args[0]); SetDescription(args[1]); } } public class MyWaitFormViewModel { protected ISplashScreenService SplashScreenService { get { return this.GetService<ISplashScreenService>(); } } public async System.Threading.Tasks.Task Wait() { SplashScreenService.ShowSplashScreen("MyWaitForm"); SplashScreenService.SetSplashScreenState(new string[] { "Please, wait", "In progress..." }); SplashScreenService.HideSplashScreen(); } }
- Call the SetSplashScreenState method with a complex object as a parameter. This object should contain an enumerator value and the required data. You can use
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
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).
Folder Browser Dialog Service
Interface
Managed Controls
None.
Global Registration
This Service is already registered.
Local Registration
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).
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.
//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
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
Method Variations
There are three possible method arguments: viewModel, parentViewModel, and parameter. However, there can be only two possible extension method combinations.
- viewModel: create a child ViewModel (including its parent and required parameters), and pass this instance to a View.
- 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:
//postpone all data injection
ViewModelInjectionPolicy.DenyViewModelInjection();
//postpone parameter injection
ViewModelInjectionPolicy.DenyImmediateParameterInjection();
//postpone parentViewModel injection
ViewModelInjectionPolicy.DenyImmediateParentViewModelInjection();