C#
WPF
Xaml
MVVM
PRISM

MVVMでMessageBoxを使用する

やりたいこと

ViewModelからメッセージボックスを表示する。

実装

メッセージボックスを表示するトリガーアクションを作成する。

トリガーアクション
using Prism.Interactivity.InteractionRequest;
using System.Windows;
using System.Windows.Interactivity;

namespace Sample {
    public class MessageBoxAction : TriggerAction<FrameworkElement> {
        protected override void Invoke(object parameter) {
            var args = parameter as InteractionRequestedEventArgs;
            if (args == null)
                return;

            var confirmation = args.Context as MessageBoxNotification;
            if (confirmation != null)
                confirmation.Result = MessageBox.Show(
                    confirmation.Message,
                    confirmation.Title,
                    confirmation.Button,
                    confirmation.Image,
                    confirmation.DefaultButton
                );

            args.Callback();
        }
    }
}
通知クラス
using Prism.Interactivity.InteractionRequest;
using System.Windows;

namespace Sample {
    public class MessageBoxNotification : Notification {
        public string Message { get; set; }
        public MessageBoxButton Button { get; set; }
        public MessageBoxImage Image { get; set; }
        public MessageBoxResult DefaultButton { get; set; }
        public MessageBoxResult Result { get; set; }
    }
}

使い方

XAML
<Window x:Class="Sample.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:prism="http://prismlibrary.com/"
        xmlns:local="clr-namespace:Sample"
        Title="MainView" Height="300" Width="300">
    <i:Interaction.Triggers>
        <prism:InteractionRequestTrigger SourceObject="{Binding OpenMessageBoxRequest, Mode=OneWay}">
            <local:MessageBoxAction/>
        </prism:InteractionRequestTrigger>
    </i:Interaction.Triggers>
    <Grid>
        <TextBox />
    </Grid>
</Window>
ViewModel
using Prism.Interactivity.InteractionRequest;
using System.Windows;

namespace Sample {
    public class MainViewModel {
        public InteractionRequest<MessageBoxNotification> OpenMessageBoxRequest { get; }
            = new InteractionRequest<MessageBoxNotification>();

        private MessageBoxResult OpenMessageBox(string title, MessageBoxImage icon, MessageBoxButton button, MessageBoxResult defaultButton, string message) {
            var notification = new MessageBoxNotification() {
                Title = title,
                Message = message,
                Button = button,
                Image = icon,
                DefaultButton = defaultButton
            };
            OpenMessageBoxRequest.Raise(notification);

            return notification.Result;
        }
    }
}