How have you successfully implemented MessageBox.Show() functionality in MVVM?

Viewed 24701

I've got a WPF application which calls MessageBox.Show() way back in the ViewModel (to check if the user really wants to delete). This actually works, but goes against the grain of MVVM since the ViewModel should not explicitly determine what happens on the View.

So now I am thinking how can I best implement the MessageBox.Show() functionality in my MVVM application, options:

  1. I could have a message with the text "Are you sure...?" along with two buttons Yes and No all in a Border in my XAML, and create a trigger on the template so that it is collapsed/visible based on a ViewModelProperty called AreYourSureDialogueBoxIsVisible, and then when I need this dialogue box, assign AreYourSureDialogueBoxIsVisible to "true", and also handle the two buttons via DelegateCommand back in my ViewModel.

  2. I could also somehow try to handle this with triggers in XAML so that the Delete button actually just makes some Border element appear with the message and buttons in it, and the Yes button did the actually deleting.

Both solutions seem to be too complex for what used to be a couple lines of code with MessageBox.Show().

In what ways have you successfully implemented Dialogue Boxes in your MVVM applications?

13 Answers

Services to the rescue. Using Onyx (disclaimer, I'm the author) this is as easy as:

public void Foo()
{
    IDisplayMessage dm = this.View.GetService<IDisplayMessage>();
    dm.Show("Hello, world!");
}

In a running application, this will indirectly call MessageBox.Show("Hello, world!"). When testing, the IDisplayMessage service can be mocked and provided to the ViewModel to do what ever you want to accomplish during the test.

Of the two you mention, I prefer option #2. The Delete button on the page just makes the "Confirm Delete Dialog" appear. The "Confirm Delete Dialog" actually kicks off the Delete.

Have you checked out Karl Shifflett's WPF Line Of Business Slides and Demos? I know he does something like this. I'll try to remember where.

EDIT: Check out Demo #11 "Data Validation in MVVM" (EditContactItemsControlSelectionViewModel.DeleteCommand). Karl calls a popup from the ViewModal (What!? :-). I actually like your idea better. Seems easier to Unit Test.

There is so many answers on this topic that vary from creating a custom class to using third party libraries. I would say use a third party library if you want cool pop ups with nice visuals.

But if you just want to use the regular message box from microsoft for your WPF app here is an MVVM/unit test friendly implementation:

Initially I thought I would just inherit from message box and wrap it with an interface but I couldn't due to Message box not having a public constructor, so here is the "easy" solution:

Decompiling Message box in visual studio you can see all the method overloads, I checked which ones I wanted then created a new class and added the methods, wrapped it with an interface and ta-da! Now you can use ninject to bind the interface and class, inject it and use Moq to unit test e.t.c.

Create an interface (only added a few of the overloads as I don't need them all):

public interface IMessageBox
    {
        /// <summary>Displays a message box that has a message, title bar caption, and button; and that returns a result.</summary>          
        MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button);

        /// <summary>Displays a message box that has a message, title bar caption, button, and icon; and that returns a result.</summary>           
        MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon);

        /// <summary>Displays a message box that has a message and title bar caption; and that returns a result.</summary>            
        MessageBoxResult Show(string messageBoxText, string caption);
    }

Then we have the class that will inherit from it:

public class MessageBoxHelper : IMessageBox
    {
        /// <summary>Displays a message box that has a message, title bar caption, button, and icon; and that returns a result.</summary>            
        public MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button,
            MessageBoxImage icon)
        {
            return MessageBox.Show(messageBoxText, caption, button, icon, MessageBoxResult.None,
                MessageBoxOptions.None);
        }

        /// <summary>Displays a message box that has a message, title bar caption, and button; and that returns a result.</summary>            
        public MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
        {
            return MessageBox.Show(messageBoxText, caption, button, MessageBoxImage.None, MessageBoxResult.None,
                MessageBoxOptions.None);
        }

        /// <summary>Displays a message box that has a message and title bar caption; and that returns a result.</summary>            
        public MessageBoxResult Show(string messageBoxText, string caption)
        {
            return MessageBox.Show(messageBoxText, caption, MessageBoxButton.OK, MessageBoxImage.None,
                MessageBoxResult.None, MessageBoxOptions.None);
        }

        /// <summary>Displays a message box that has a message and that returns a result.</summary>           
        public MessageBoxResult Show(string messageBoxText)
        {
            return MessageBox.Show(messageBoxText, string.Empty, MessageBoxButton.OK, MessageBoxImage.None,
                MessageBoxResult.None, MessageBoxOptions.None);
        }
    }

Now just use this when injecting e.t.c and boom u have a flimsy abstraction that will do the trick... which is fine depending on where you will use it. My case is a simple app only meant to do a few things, so no point over engineering a solution. Hope this helps someone.

I would just throw it from the VM. I dont want to have to use someone else's service or write my own just to throw a messagebox.

I've implemented a Behavior that listens to a Message from the ViewModel. It's based on Laurent Bugnion solution, but since it doesn't use code behind and is more reusable, I think it's more elegant.

Check it out here

Cache of the broken link

Working fine [MVVM]

if (System.Windows.MessageBox.Show("Are you need to delete?", "", 
   System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
{
    // Do your action
}
Related