Dialogs In WPF (MVVM)

Datetime:2016-08-23 01:24:47          Topic: WPF  MVVM Model           Share

There are a lot of different articles on this topic and a lot of different solutions, simple based on static helper or service classes and more complex based on WPF dependency properties. All of them have their own pros and cons. I will not discuss about advantages and disadvantages of vary solutions, but I wish to tell about the solution I like more. Probably it has its own positive and negative points as well, hope we will know about them during a feedback. I will illustrate the solution in step-by-step manner from very basics of MVVM to complexity of dependency injection. While the narration I will not give any definitions, hope you will find them in vary sources if you enjoy the solution.

Part 1:MVVM

Step 1.To start our work let’s create new WPF application project and save it with name WpfApplication1 .

Step 2.We will follow MVVM (Model - View - ViewModel) pattern to develop our simple project. At this step let’s organize project structure and add new folders: Models , ViewModels and Views .

Step 3.Move MainWindow.xaml to Views folder and edit namespaces in xaml and code behind files taking new placement into consideration:

  • MainWindow.xaml : x : Class ="WpfApplication1.Views.MainWindow" ;
  • MainWindow.xaml.cs : namespace WpfApplication1.Views .

Step 4. Set StartupUri property in App.xaml to "Views/MainWindow.xaml" and run application to check it still works.

Step 5. To implement commands logic we have to use a RelayCommand class, you can download it  and save in project root folder. Include RelayCommand.cs in project and change namespace to WpfApplication1 .

Step 6.We will execute RelayCommand with parameter further, for this purpose make some changes:

  • replace all instances of “ Action execute ” with “ Action < object > execute ”;
  • replace “ this .execute(); ” with “ this .execute(parameter); ” in public void Execute(object parameter) method.

or find any other implementation for RelayCommand with parameters.

Step 7.At Steps 7-11 we will create a view model for MainWindow of our project. Add new public class in ViewModels folder and name it MainWindowViewModel .

Step 8.Add using of System.Windows.Input namespace to MainWindowViewModel.cs:

using System.Windows.Input;

Step 9.Add private field openDialogCommand and corresponding public property:

private ICommand openDialogCommand = null;  
public ICommand OpenDialogCommand  
{  
    get { return this.openDialogCommand; }  
    set { this.openDialogCommand = value; }  
}  

Step 10.Add private void method OnOpenDialog :

private void OnOpenDialog(object parameter)  
{  
  
}  

Step 11.Add parameterless constructor for MainWindowViewModel and initialize private field openDialogComand through RelayCommand instance:

public MainWindowViewModel()  
{  
    this.openDialogCommand = new RelayCommand(OnOpenDialog);  
}  

Step 12.At steps 12-16 we will associate main window with its view model. Build project. Open App.xaml and add namespace for ViewModels folder:

xmlns:viewModels="clr-namespace:WpfApplication1.ViewModels"   

Step 13.Add resource for MainWindowViewModel to Application.Resources section:

<viewModels:MainWindowViewModel x:Key="MainWindowViewModel" />   

Step 14.Open MainWindow.xaml and declare DataContext property for Window node (along with Title , Height and Width properties):

DataContext="{StaticResource ResourceKey=MainWindowViewModel}"   

Step 15.Add button to Grid node in markup of MainWindow.xaml and specify a Command property through binding to OpenDialogCommand property of data context:

<Button Content="Button" ... Command="{Binding OpenDialogCommand}" />   

Step 16.Put a breakpoint at the open curly brace of OnOpenDialog method in MainWindowViewModel and run the project. Click button and notice the project’s flow stopped at the breakpoint.

PART 2. DIALOG STRUCTURE

Step 17.In this part we will create a base for a modal dialog window. Add a new folder Dialogs to project tree and two subfolders - DialogService and DialogYesNo .

Step 18.All our dialogs must return a result of choice made by user. Add a new item DialogResultEnum.cs to DialogService folder, replace class with enum and define structure with possible dialog result values, for example:

public enum DialogResult  
{  
    Undefined,  
    Yes,  
    No  
}  

Step 19.Add a new Window (WPF) to DialogService folder and name it DialogWindow .

Step 20.Add a property WindowStartupLocation to Window node and replace Grid section in DialogWindow markup with ContentPresenter node:

<Window x:Class="WpfApplication1.Dialogs.DialogService.DialogWindow"  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
        Title="DialogWindow" Height="300" Width="300"  
        WindowStartupLocation="CenterScreen">  
     <ContentPresenter x:Name="ContentPresenter" Content="{Binding}"></ContentPresenter>  
</Window>   

Step 21.Add a new public static class DialogService.cs to DialogService folder and define public static method OpenDialog which returns DialogResult :

public static DialogResult OpenDialog()  
{  
    DialogWindow win = new DialogWindow();  
    win.ShowDialog();  
    return DialogResult.Undefined;  
}  

Step 22.Get back to MainWindowViewModel , and modify OnOpenDialog method:

private void OnOpenDialog(object parameter)  
{  
    Dialogs.DialogService.DialogResult result =  
        Dialogs.DialogService.DialogService.OpenDialog();  
}  

Step 23.Run project, put a breakpoint at closing curly brace in OnOpenDialog method and click button in main window. Dialog window should appear and result variable should have a DialogResult.Undefined value after closing the dialog.

PART 3. DIALOG VIEW

Step 24.In this part we will add a view for our modal dialog and define some logic. Add new public abstract class DialogViewModelBase to DialogService folder:

public abstract class DialogViewModelBase  
{  
  
}  

Step 25.Add new user control (WPF) to DialogYesNo folder and name it DialogYesNoView , place two buttons as a content of the control:

<UserControl x:Class="WpfApplication1.Dialogs.DialogYesNo.DialogYesNoView"  
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
             mc:Ignorable="d"  
             d:DesignHeight="100" d:DesignWidth="300">  
    <Grid Margin="4">  
        <Button Content="Yes" HorizontalAlignment="Left" Margin="135,70,0,0" VerticalAlignment="Top" Width="75"/>  
        <Button Content="No" HorizontalAlignment="Left" Margin="215,70,0,0" VerticalAlignment="Top" Width="75"/>  
    </Grid>  
</UserControl>   

Step 26.Add a new class to DialogYesNo folder and name it DialogYesNoViewModel , make DialogYesNoViewModel derived from DialogViewModelBase .

Step 27.Add two commands to process Yes and No buttons click (similarly for button at main window, see Steps 8-9 ):

class DialogYesNoViewModel : DialogViewModelBase  
{  
    private ICommand yesCommand = null;  
    public ICommand YesCommand  
    {  
        get { return yesCommand; }  
        set { yesCommand = value; }  
    }  
  
    private ICommand noCommand = null;  
    public ICommand NoCommand  
    {  
        get { return noCommand; }  
        set { noCommand = value; }  
    }  
  
    public DialogYesNoViewModel()  
    {  
        this.yesCommand = new RelayCommand(OnYesClicked);  
        this.noCommand = new RelayCommand(OnNoClicked);  
    }  
  
    private void OnYesClicked(object parameter)  
    {  
  
    }  
  
    private void OnNoClicked(object parameter)  
    {  
  
    }  
}  

Step 28.Modify DialogYesNoView and add Command properties to Yes and No buttons. Pay attention to CommandParameter property - we will pass a reference to the hosting window as a parameter to commands:

<Button Content="Yes" HorizontalAlignment="Left" Margin="135,70,0,0" VerticalAlignment="Top" Width="75"   
        Command="{Binding YesCommand}"   
        CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>  
<Button Content="No" HorizontalAlignment="Left" Margin="215,70,0,0" VerticalAlignment="Top" Width="75"   
        Command="{Binding NoCommand}"  
        CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>   

Step 29.Get back to App.xaml and add namespace for DialogYesNo folder:

xmlns:dialogYesNo="clr-namespace:WpfApplication1.Dialogs.DialogYesNo"   

Step 30.Append an Application.Resources section with a resource for data template to associate DialogYesNoViewModel with DialogYesNoView :

<DataTemplate DataType="{x:Type dialogYesNo:DialogYesNoViewModel}">  
    <dialogYesNo:DialogYesNoView></dialogYesNo:DialogYesNoView>  
</DataTemplate>   

Step 31.Get back to DialogWindow.xaml and add SizeToContent property to Window node along with WindowStartupLocation property:

SizeToContent="WidthAndHeight"   

Step 32.Modify signature of OpenDialog static method in DialogService , let the method accept a parameter of type DialogViewModelBase and define win variable’s DataContext property:

public static DialogResult OpenDialog(DialogViewModelBase vm)  
{  
    DialogWindow win = new DialogWindow();  
    win.DataContext = vm;  
    win.ShowDialog();  
    return DialogResult.Undefined;  
}  

Step 33.Get back to MainWindowViewModel to modify call of DialogService.OpenDialog() . Create instance of DialogViewModelBase instantiated with DialogYesNoViewModel and pass it as an argument to DialogService.OpenDialog() :

private void OnOpenDialog(object parameter)  
{  
    Dialogs.DialogService.DialogViewModelBase vm =  
        new Dialogs.DialogYesNo.DialogYesNoViewModel();  
    Dialogs.DialogService.DialogResult result =  
        Dialogs.DialogService.DialogService.OpenDialog(vm);  
}  

Now we have a modal YesNo dialog with empty commands to process buttons click, and the dialog still returns DialogResult.Undefined value after closing.

PART 4. DIALOG RESULT

Step 34.Get back to DialogViewModelBase , add public property UserDialogResult of type DialogResult :

public DialogResult UserDialogResult  
{  
    get;  
    private set;  
}  

Step 35.Add void method CloseDialogWithResult to close dialog window:

public void CloseDialogWithResult(Window dialog, DialogResult result)  
{  
    this.UserDialogResult = result;  
    if (dialog != null)  
        dialog.DialogResult = true;  
}  

Step 36.Get back to DialogYesNoViewModel and define methods OnYesClicked and OnNoClicked :

private void OnYesClicked(object parameter)  
{  
    this.CloseDialogWithResult(parameter as Window, DialogResult.Yes);  
}  
  
private void OnNoClicked(object parameter)  
{  
    this.CloseDialogWithResult(parameter as Window, DialogResult.No);  
}  

Step 37.Modify OpenDialog method in DialogService - add result variable and set its value to UserDialogResult property of hosting window data context:

public static DialogResult OpenDialog(DialogViewModelBase vm)  
{  
    DialogWindow win = new DialogWindow();  
    win.DataContext = vm;  
    win.ShowDialog();  
    DialogResult result =  
        (win.DataContext as DialogViewModelBase).UserDialogResult;  
    return result;  
}  

At this moment our dialog returns a result of type DialogResult . Put a breakpoint to a closing curly brace in OnOpenDialog method in MainWindowViewModel , run project and click a button. Modal YesNo dialog will open. Click Yes or No button, dialog will be closed. Project flow will stop at break point and result variable will have a value, depend on which button was clicked.

PART 5. IMPROVEMENT

Step 38.Add Message property of type string and constructor with parameter to DialogViewModelBase :

public string Message  
{  
    get;  
    private set;  
}  
  
public DialogViewModelBase(string message)  
{  
    this.Message = message;  
}  

Step 39.Modify constructor in DialogYesNoViewModel :

public DialogYesNoViewModel(string message)  
    : base(message)  
{  
    this.yesCommand = new RelayCommand(OnYesClicked);  
    this.noCommand = new RelayCommand(OnNoClicked);  
}  

Step 40.Add string argument when instantiate variable of type DialogViewModelBase with DialogYesNoViewModel in OnOpenDialog method in MainWindowViewModel :

private void OnOpenDialog(object parameter)  
{  
    Dialogs.DialogService.DialogViewModelBase vm =  
        new Dialogs.DialogYesNo.DialogYesNoViewModel("Question");  
    Dialogs.DialogService.DialogResult result =  
        Dialogs.DialogService.DialogService.OpenDialog(vm);  
}  

Step 41.Add a Label element to DialogYesNoView.xaml and set its Content property connected with Message property of data context:

<Label Content="{Binding Message}" .../>   

Step 42.Modify signature of OpenDialog method in DialogService and add second parameter of type Window , set Owner property of DialogWindow instance to parameter value:

public static DialogResult OpenDialog(DialogViewModelBase vm, Window owner)  
{  
    DialogWindow win = new DialogWindow();  
    if(owner != null)  
        win.Owner = owner;  
    win.DataContext = vm;  
    win.ShowDialog();  
    DialogResult result =  
        (win.DataContext as DialogViewModelBase).UserDialogResult;  
    return result;  
}  

Step 43.Add second argument to call OpenDialog method from OnOpenDialog method in MainWindowViewModel :

private void OnOpenDialog(object parameter)  
{  
    Dialogs.DialogService.DialogViewModelBase vm =  
        new Dialogs.DialogYesNo.DialogYesNoViewModel("Question");  
    Dialogs.DialogService.DialogResult result =  
        Dialogs.DialogService.DialogService.OpenDialog(vm, parameter as Window);  
}  

Step 44.Add CommandParameter property to Button element in MainWindow.xaml :

<Button Content="Button" ... Command="{Binding OpenDialogCommand}"  
        CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>   

Step 45.Change WindowStartupLocation property to “ CenterOwner ” in DialogWindow.xaml .

PART 6. DEPENDENCY INJECTION

Step 46.Create subfolder DialogFacade in Dialogs folder.

Step 47.Add public interface IDialogFacade :

public interface IDialogFacade  
{  
    DialogResult ShowDialogYesNo(string message, Window owner);  
}  

Step 48.Add class DialogFacade , implement IDialogFacade and add private ShowDialog method by copying content of method from DialogService :

public class DialogFacade : IDialogFacade  
{  
    public DialogFacade()  
    {  
  
    }  
  
    public DialogResult ShowDialogYesNo(string message, Window owner)  
    {  
        DialogViewModelBase vm = new DialogYesNo.DialogYesNoViewModel(message);  
        return this.ShowDialog(vm, owner);  
    }  
  
    private DialogResult ShowDialog(DialogViewModelBase vm, Window owner)  
    {  
        DialogWindow win = new DialogWindow();  
        if (owner != null)  
            win.Owner = owner;  
        win.DataContext = vm;  
        win.ShowDialog();  
        DialogResult result =  
            (win.DataContext as DialogViewModelBase).UserDialogResult;  
        return result;  
    }  
}  

Step 49.Install Ninject Nuget package.

Step 50.Add IoC subfolder to project root folder.

Step 51.Add new class and name it Module , add two usings to work with Ninject:

using Ninject;  
using Ninject.Modules; 

Step 52.Derive Module class from NinjectModule abstract class and implement it:

class Module : NinjectModule  
{  
    public override void Load()  
    {  
        Bind<IDialogFacade>().To<DialogFacade>().InSingletonScope();  
        Bind<MainWindowViewModel>().ToSelf();  
    }  
}  

Step 53.Add new class Container and implement access to Ninject kernel using singleton pattern:

public class Container  
{  
    public IKernel Kernel  
    {  
        get;  
        private set;  
    }  
  
    private static volatile Container instance = null;  
    private static object syncRoot = new Object();  
  
    private Container()  
    {  
        this.Kernel = new Ninject.StandardKernel();  
        this.Kernel.Load(new Module());  
    }  
  
    public static Container Instance  
    {  
        get  
        {  
            if (instance == null)  
            {  
                lock (syncRoot)  
                {  
                    if (instance == null)  
                        instance = new Container();  
                }  
            }  
            return instance;  
        }  
    }  
}  

Step 54.Add private field named dialogFacade to MainWindowViewModel and edit constructor for accepting IDialogFacade parameter:

public class MainWindowViewModel  
{  
    private IDialogFacade dialogFacade = null;  
    ...  
    public MainWindowViewModel(IDialogFacade dialogFacade)  
    {  
        this.dialogFacade = dialogFacade;  
        this.openDialogCommand = new RelayCommand(OnOpenDialog);  
    }  
    ...  
}  

Step 55.Add a new class ViewModelLocator to ViewModels folder:

using Ninject;  
  
public class ViewModelLocator  
{  
    private MainWindowViewModel mainWindowViewModel = null;  
    public MainWindowViewModel MainWindowViewModel  
    {  
        get { return mainWindowViewModel; }  
        set { mainWindowViewModel = value; }  
    }  
  
    public ViewModelLocator()  
    {  
        this.mainWindowViewModel =  
            IoC.Container.Instance.Kernel.Get<MainWindowViewModel>();  
    }  
}  

Step 56.Remove MainVindowViewModel resource and add ViewModelLocator resource to App.xaml :

<Application x:Class="WpfApplication2.App"  
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
             xmlns:viewModels="clr-namespace:WpfApplication2.ViewModels"  
             xmlns:dialogYesNo="clr-namespace:WpfApplication2.Dialogs.DialogYesNo"  
             StartupUri="Views/MainWindow.xaml">  
    <Application.Resources>  
        <viewModels:ViewModelLocator x:Key="ViewModelLocator" />  
        <DataTemplate DataType="{x:Type dialogYesNo:DialogYesNoViewModel}">  
            <dialogYesNo:DialogYesNoView></dialogYesNo:DialogYesNoView>  
        </DataTemplate>  
    </Application.Resources>  
</Application>   

Step 57.Change DataContext property in MainWindow.xaml :

DataContext="{Binding MainWindowViewModel, Source={StaticResource ResourceKey=ViewModelLocator}}"   

Step 58.Call ShowDialogYesNo method of dialogFacade object from OnOpenDialog method in MainWindowViewModel :

private void OnOpenDialog(object parameter)  
{  
    Dialogs.DialogService.DialogResult result =  
        this.dialogFacade.ShowDialogYesNo("Question", parameter as Window);  
}  

Read more articles on WPF:





About List