Back to Devexpress

DialogService

wpf-17467-mvvm-framework-services-predefined-set-dialog-services-dialogservice.md

latest11.6 KB
Original Source

DialogService

  • Oct 12, 2023
  • 12 minutes to read

The DialogService class allows you to show a modal dialog window from a View Model.

View Example: Use DialogService to Show a Modal Dialog Window

Related services:

Show a Dialog

Follow the steps below to define a simple dialog window and show it from the View Model:

  1. Assign a DialogService service to your View in any of the following ways:

  2. Define dialog content. The following code sample creates a data template and assigns it to the ViewTemplate property:

  3. Use the DialogStyle and DialogWindowStartupLocation properties to specify the dialog window’s startup location and additional settings:

  4. Access the service from the View Model. The following code sample demonstrates how to access the service from a ViewModelBase descendant View Model:

  5. Create a View Model command that calls the DialogService.ShowDialog method to invoke the dialog window:

  6. Bind the button’s Command property to the created command:

Bind Dialog Content to Data

Follow the steps in this section to create a dialog with two data-bound editors (First Name and Last Name). The code binds editor values to properties in your View Model:

  1. Use the ViewTemplate property to define the dialog layout:

  2. Create a dialog View Model:

  3. Create a new instance of the DialogViewModel class and pass this instance to the DialogService.ShowDialog method when a user invokes the dialog:

Define Dialog Buttons

You can use one of the following techniques to define dialog buttons.

Predefined Buttons

Pass a MessageButton enumeration value to the ShowDialog method. In this case, the dialog returns the result of the MessageResult type.

csharp
[Command]
public void ShowDialog() {
    MessageResult result;
    result = DialogService.ShowDialog(
        dialogButtons: MessageButton.OKCancel,
        title: "Edit Dialog",
        viewModel: this
    );
    if (result == MessageResult.OK) {
        // ...
    }
}
vb
<Command>
Public Sub ShowDialog()
    Dim result As MessageResult
    result = DialogService.ShowDialog(dialogButtons:=MessageButton.OKCancel, title:="Edit Dialog", viewModel:=Me)

    If result = MessageResult.OK Then
        ' ...
    End If
End Sub

UICommand Buttons

Pass a collection of the UICommand objects to the ShowDialog method. In this case, the dialog returns a result of the UICommand type.

csharp
[Command]
public void ShowDialog() {
    // Specify the Apply button:
    var buttonApply = new UICommand() {
        Id = "apply",
        Caption = "Apply",
        Command = new DelegateCommand<CancelEventArgs>(
            cancelArgs => {
                try {
                    // Your "Apply" method 
                }
                catch (Exception e) {
                    // Process errors
                    // ...
                    cancelArgs.Cancel = true;
                }
            },
            // Disable the button if one of the fields is empty:
            cancelArgs => !string.IsNullOrEmpty(dialogViewModel.FirstName) && !string.IsNullOrEmpty(dialogViewModel.LastName)
        ),
        Glyph = new Uri("pack://application:,,,/DevExpress.Images.v25.2;component/SvgImages/Icon Builder/Actions_CheckCircled.svg"),
        IsDefault = true,
        IsCancel = false
    };
    // Specify the Cancel button:
    var buttonCancel = new UICommand() {
        Id = "cancel",
        Caption = "Cancel",
        Command = new DelegateCommand(() => { /* Your "Cancel" method */ }),
        Glyph = new Uri("pack://application:,,,/DevExpress.Images.v25.2;component/SvgImages/Icon Builder/Actions_DeleteCircled.svg"),
        IsDefault = false,
        IsCancel = true
    };

    UICommand result;
    result = DialogService.ShowDialog(
        dialogCommands: new UICommand[] { buttonApply, buttonCancel },
        title: "Edit Dialog",
        viewModel: this
    );

    if (result == buttonApply) {
        // ...
    }
}
vb
<Command>
Public Sub ShowDialog()
    ' Specify the Apply button:
    Dim buttonApply = New UICommand() With {
        .Id = "apply",
        .Caption = "Apply",
        .Command = New DelegateCommand(Of CancelEventArgs)(Function(cancelArgs)
            Try
                ' Your "Apply" method 
            Catch e As Exception
                ' Process errors
                ' ...
                cancelArgs.Cancel = True
            End Try
        End Function,
        ' Disable the button if one of the fields is empty:
        Function(cancelArgs) Not String.IsNullOrEmpty(dialogViewModel.FirstName) AndAlso Not String.IsNullOrEmpty(dialogViewModel.LastName)),
        .Glyph = New Uri("pack://application:,,,/DevExpress.Images.v25.2;component/SvgImages/Icon Builder/Actions_CheckCircled.svg"),
        .IsDefault = True,
        .IsCancel = False
    }
    ' Specify the Cancel button:
    Dim buttonCancel = New UICommand() With {
        .Id = "cancel",
        .Caption = "Cancel",
        .Command = New DelegateCommand(Function()
            ' Your "Cancel" method
        End Function),
        .Glyph = New Uri("pack://application:,,,/DevExpress.Images.v25.2;component/SvgImages/Icon Builder/Actions_DeleteCircled.svg"),
        .IsDefault = False,
        .IsCancel = True
    }
    Dim result As UICommand
    result = DialogService.ShowDialog(dialogCommands:=New UICommand() {buttonApply, buttonCancel}, title:="Edit Dialog", viewModel:=Me)

    If result = buttonApply Then
        ' ...
    End If
End Sub

Asynchronous Buttons

The DialogService can display asynchronous buttons. These buttons indicate whether the associated asynchronous operation is in progress.

To display an asynchronous button, you can follow the same steps as in the previous section, with two adjustments:

csharp
var buttonApplyAsync = new UICommand(
    id: "applyAsync",
    caption: "Apply Async",
    command: new AsyncCommand<CancelEventArgs>(
        async cancelArgs => {
            try {
                await // Your asynchronous "Apply" method 
            }
            catch (Exception e) {
                // Process errors
                // ...
                cancelArgs.Cancel = true;
            }
        },
        // Disable the button if one of the fields is empty:
        cancelArgs => !string.IsNullOrEmpty(dialogViewModel.FirstName) && !string.IsNullOrEmpty(dialogViewModel.LastName)
    ),
    asyncDisplayMode: AsyncDisplayMode.Wait,
    isDefault: false,
    isCancel: false
);
vb
Dim buttonApplyAsync = New UICommand(
    id:="applyAsync", 
    caption:="Apply Async", 
    command:=New AsyncCommand(Of CancelEventArgs)(Async Function(cancelArgs)
        Try
            Await ' Your asynchronous "Apply" method 
        Catch e As Exception
            ' Process errors
            ' ...
            cancelArgs.Cancel = True
        End Try
    End Function,
    ' Disable the button if one of the fields is empty:
    Function(cancelArgs) Not String.IsNullOrEmpty(dialogViewModel.FirstName) AndAlso Not String.IsNullOrEmpty(dialogViewModel.LastName)), 
    asyncDisplayMode:=AsyncDisplayMode.Wait, 
    isDefault:=False, 
    isCancel:=False
)

Refer to the following help topic for more information: Asynchronous Commands.

Use Custom Dialog Buttons

Use Any Control as a Dialog Button

You can define custom buttons in the dialog View and use these buttons instead of standard dialog buttons:

  1. Define custom buttons in the DialogView :

  2. Attach the CurrentDialogService to the DialogView to access the dialog window from its View Model:

  3. Create commands that use the CurrentDialogService.Close method to close the dialog window and specify the dialog result:

  4. Hide the standard dialog buttons:

View Example: Close an Opened Dialog and Specify the Dialog Result

Use the Built-in Dialog Button Type to Create Customized Buttons

Dialog buttons are objects of the ThemedWindowDialogButton class. You can add these elements to the dialog View and specify their position and appearance:

  1. Create ThemedWindowDialogButton objects, specify their properties, and place these buttons in the ThemedWindowDialogButtonsControl container:

  2. Hide the standard dialog buttons:

View Example: Customize Dialog Buttons

Execute an Action when a User Closes the Dialog

You can use the CurrentDialogService.ClosingCommand property to process the close dialog operation.

  1. Create a command that is executed when a user closes the dialog. The following code sample displays a confirmation message when a user clicks the dialog window’s Close button (X):

  2. Bind the CurrentDialogService.ClosingCommand property to the created command:

View Example: Customize Dialog Buttons

See Also

WinUIDialogService

CurrentDialogService