IResult and System Dialogs

Oct 19, 2010 at 4:23 PM

Hi,

What is the recommended best practice regarding the interaction between ViewModels and things like system file dialogs and MessageBox? I've read the documentation about "IResult and Coroutines" and on reading this I've created a class that implements IResult and wraps a MessageBox. This wrapper class exposes a property that allows me access to MessageBoxResult from the calling VM. Here is the wrapper class:

public class Messenger : IResult
    {
        private readonly string _message;
        private MessageBoxResult _result;

        public Messenger(string message)
        {
            _message = message;
        }

        public MessageBoxResult Result { get { return _result; } }

        public void Execute(ActionExecutionContext context)
        {
            var view = context.View as FrameworkElement;
            while (view != null)
            {
                var window = view as Window;
                if (window != null)
                {
                    _result = MessageBox.Show(window, _message, "App title", MessageBoxButton.OK, MessageBoxImage.Information);
                    break;
                }
                view = view.Parent as FrameworkElement;
            }
            Completed(this, new ResultCompletionEventArgs());
        }

        public event EventHandler<ResultCompletionEventArgs> Completed;
    }

This wrapper in invoked from a ViewModel action method, thus:

 

public IEnumerable<IResult> Save()
{
    var result = new Messenger("your stuff has been saved!");
    yield return result;
    if( result.Result == MessageBoxResult.OK ) 
    {
        // Do stuff here..
    }
}

 

My questions are: is this best way to interact with system dialogs? And, is exposing a property like the above Messenger class, the best way to get results back to the VM?

Cheers

Barry Carr

Coordinator
Oct 19, 2010 at 4:40 PM

FWIW, I've used a similar technique myself. It's hard to say if it's a "best practice." But I've found it works nicely.

Oct 19, 2010 at 4:43 PM

Thanks, Rob. That's very reassuring.

Cheers

Barry