Open a Dialog with MVVM

82 Views Asked by At

I'm trying to show a dialog window when something throws an error in my application. When the viewmodel wants to launch a dialog, it fires an event and the View's code behind answers by creating a new Dialog window and showing it. The problem that I have is that I cannot pass any info to the dialog (like the error message), because the DialogViewModel isn't loaded when I create the DialogView.

I tried this on the DialogView constructor:

    public DialogView() {
        InitializeComponent();

        var vm = (DialogViewModel)DataContext;
        if( vm != null ) {
            vm.ErrorInfo= "Sample error message";
        }

    }

but this doesn't work because the DialogViewModel is null.

1

There are 1 best solutions below

0
BionicCode On
  1. You can pass the error info via the event data to the parent window of the dialog.
  2. Let the parent window create the dialog's view model instance and initialize it with the event data.
  3. Let the parent window create the dialog window.
  4. Let the parent window set the pre-initialized dialog view model to the DataContext of the dialog (or Content property, depending on how you handle the layout of the dialog).
  5. Let the parent windo show the dialog.

MainWindow.xaml.cs

partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    var mainViewModel = new MainViewModel();

    // TODO::Create the ErrorChanged event and the ErrorChangedEventArgs (EventHandler<ErrorChangedEventArgs>)
    mainViewModel.ErrorChanged += OnViewModelErrorChanged;
    this.DataContext = mainViewModel;
  }

  private void OnViewModelErrorChanged(object sender, ErrorChangedEventArgs e)
  {
    // Consider to pass the error info to the constructor
    var errorDialogViewModel = new DialogViewModel() { ErrorInfo = e.Message };
    var errorDialog = new DialogView() { DataContext = errorDialogViewModel };
    erorDialog.ShowDialog();
  }
}