Casperonian
Casperonian

Reputation: 184

Implementing WPF MVVM Dialog Service

I'm trying to implement the "MVVM recommended" way of handling multiple views/windows in the application thru a DialogService. However, I encountered a difficulty in implementing closing the parent view after showing the child view. Here's my implementation so far. What is the best strategy for WPF MVVM to handle such scenario?

DialogService.cs (I try to make this generic so that it can show and close any windows)

public class DialogService : IDialogService
{
    /// <summary>
    /// Closes the specified window screen
    /// </summary>
    /// <param name="dialogWindow"></param>
    public void CloseDialog(Window dialogWindow)
    {
        if ( dialogWindow != null )
            dialogWindow.Close ( );       
    }

    /// <summary>
    /// Shows the specified window screen
    /// </summary>
    /// <param name="dialogWindow"></param>
    public void ShowDialog(Window dialogWindow)
    {
        if ( dialogWindow != null )
            dialogWindow.ShowDialog ( );
    }
}

The view model that shows the child view is SelectPackageViewModel.cs

public SelectPackageViewModel(IPackageDataService packageDataService, IDialogService dialogService)
{
    this.packageDataService = packageDataService;
    this.dialogService = dialogService;
    LoadPackages();
    LoadCommands();
}
private void LoadCommands()
{
    CreateNewCommand = new CustomCommand(CreateNewPackage);
}
private void CreateNewPackage(object obj)
{            
    dialogService.ShowDialog(new CreatePackage());            
}

The parent view SelectPackage.cs. The child view is CreatePackage.cs

<Button Name="btnNewPackage"
    Content="New..."
    HorizontalAlignment="Center"
    Width="120"
    Height="30"
    FontSize="15" FontWeight="Bold"
    Margin="10"
    Command="{Binding CreateNewCommand}"/>

Upvotes: 3

Views: 5526

Answers (1)

FantasticFiasco
FantasticFiasco

Reputation: 1193

You can always use the NuGet package called MvvmDialogs, or look at its implementation. After all It's open source on GitHub.

Friendly advice, be aware of answers regarding MVVM that are absolute. These answers often come from developers in the learning phase, where rules and guidelines are followed without understanding their benefit. As you progress you start to question "why", and become more pragmatic. The idea that the view model shouldn't be aware of a view service is just silly. It is a view model, the view is in it's name.

Upvotes: 7

Related Questions