Alex Stefan
Alex Stefan

Reputation: 63

Correct implementation of WPF custom MessageBox using MVVM pattern

I am quite new to WPF and I have to implement a custom message box following the MVVM pattern, but without using any MVVM helper libraries. This message box will be used to give information about unexpected errors that occur in the application - a general message + the stacktrace in the details. I'm handling the DispatcherUnhandledException event for this and I'm using this custom message box in the handler for this 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 a correct use of the MVVM pattern and if not, what could I do to fix it?

Upvotes: 3

Views: 1440

Answers (2)

Michał Turecki
Michał Turecki

Reputation: 3167

Your example is a correct use of MVVM pattern as you have a separate ViewModel to which I assume you bind to and which does not know about the View.

Possibly you can simplify the ViewModel by replacing ShowMessage function (which actually does not show a message I guess) with an Exception property and set it.

Any reason why you are not using ShowDialog? You might end up having a lot of exception dialogs on screen if something will continuously go 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;
}

Upvotes: 2

Mike Burdick
Mike Burdick

Reputation: 838

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 a Dependency Injector like Unity so in my Unit Tests I can Mock the IDialogService and not have MessageBox windows popup. Another approach is to put the actual UI code in protected virtual methods and have your Unit Tests use a IDialogService that replaces the MessageBox calls.

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

Upvotes: 2

Related Questions