Correct implementation of custom WPF MessageBox using MVVM pattern

I'm new to WPF and I need to implement a custom message box that follows the MVVM pattern, but without using any MVVM helper libraries. This message field will be used to provide information on unexpected errors occurring in the application - general message + stack in detail. To do this, I am handling the DispatcherUnhandledException event and I am using this custom message box in the handler for that event.

void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        CustomMessageBoxViewModel messageBox = new CustomMessageBoxViewModel();
        messageBox.ShowMessage(e.Exception.Message, e.Exception.StackTrace);
        CustomMessageBoxWindow messageBoxWindow = new CustomMessageBoxWindow();
        messageBoxWindow.DataContext = messageBox;
        messageBoxWindow.Show();

        e.Handled = true;
    }

      

Could you tell me if this is the correct use of the MVVM pattern, and if not, what can I do to fix it?

+3


source to share


2 answers


Your example is the correct use of the MVVM pattern since you have a separate ViewModel that I assume you are binding to and which is unaware of the view.

Perhaps you can simplify the ViewModel by replacing the ShowMessage function (which doesn't actually display the message I am assuming) with the Exception property and set it.



Any reason you are not using ShowDialog? It is possible that a lot of exception dialogs will appear on the screen if something keeps going wrong.

void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
    CustomMessageBoxViewModel messageBox = new CustomMessageBoxViewModel();
    messageBox.Sender = sender;
    messageBox.Exception = e.Exception;
    CustomMessageBoxWindow messageBoxWindow = new CustomMessageBoxWindow();
    messageBoxWindow.DataContext = messageBox;
    messageBoxWindow.ShowDialog();

    e.Handled = true;
}

      

+2


source


I would create a DialogService class that implements IDialogService. This class / interface should contain whatever methods you deem appropriate for the dialogs you need.

I would also use Injector Dependency like Unity so in my tests I can swing the IDialogService and not pop up in the MessageBox. Another approach is to put the actual UI code in protected virtual methods and use IDialogService in your unit tests, which replaces the MessageBox calls.



So, in your case, I would just call something like IDialogService.DisplayError (Exception ex).

+2


source







All Articles