C# | WPF Prism Screen Navigation (Dialog)

C# WPF Prism dialog screen navigation

TechPublished 2 min read

I'll explain how to display a dialog screen (a separate window) using WPF Prism in C#.

Target Files (Example)

The files you need to code are A through D below.

Views/
 |-MainWindowView.xaml(画面遷移元) ・・・A
 |-SampleTableEditView.xaml(画面遷移先)

ViewModels/
 |-MainWindowViewModel.cs(画面遷移元) ・・・B
 |-SampleTableEditViewModel.cs(画面遷移先) ・・・C 

App.xaml.cs ・・・D

MainWindowView.xaml (source of navigation) ・・・A

①Add a Command to the button

For the button on the View that navigation starts from, add the delegate command name via Binding on Command.

<Button Content="SampleTable編集"
        FontSize="14"
        Margin="10"
        Padding="5"
        Command="{Binding SampleTableEditViewButton}"/>

MainWindowViewModel.cs (source of navigation) ・・・B

②Add an IDialogService field to the ViewModel

Add a private IDialogService field to the ViewModel that navigation starts from, and set it in the constructor.

③Add the method that runs when the button is pressed

Add the delegate command property that receives the button-press event, and implement the Execute method for when the button is pressed.

The sample code for ② and ③ above is as follows.

//// コンストラクタ
public MainWindowViewModel(IDialogService dialogService)
{
    //// 画面遷移用(ダイアログ)
    _dialogService = dialogService;

    SampleTableEditViewButton = new DelegateCommand(SampleTableEditViewButtonExecute);
}

public DelegateCommand SampleTableEditViewButton { get; }

private void SampleTableEditViewButtonExecute()
{
    //// 画面遷移処理(ダイアログ)
    _dialogService.ShowDialog(nameof(SampleTableEditView), null, null);
}

SampleTableEditViewModel.cs (navigation destination) ・・・C 

④Implement the IDialogAware interface

Implement the IDialogAware interface on the ViewModel that is the navigation destination.

⑤Change the CanCloseDialog method

Implementing IDialogAware adds the CanCloseDialog() method — write return true in it.
Returning true makes it possible to close the dialog.

▼Sample code for ④ and ⑤ above

public class SampleTableEditViewModel : BindableBase, IDialogAware
{

  //// 各種処理

  public bool CanCloseDialog()
  {
      return true;    //// true:画面を閉じる事が可能
  }
}

App.xaml.cs ・・・D

⑥Register the View inside RegisterTypes

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    //// ダイアログ画面(別画面に表示) ※ViewModelにIDialogAware実装が必要
    containerRegistry.RegisterDialog<SampleTableEditView, SampleTableEditViewModel>();

}

Any View registered with containerRegistry.RegisterDialog becomes displayable as a dialog.