9

ユーザーに検証エラーを表示したいとします。MVVMパターンでは、ビューモデルのいくつかのプロパティにバインドされたラベルを持つことができます。しかし、MVVMパターンを厳密に遵守しながら、メッセージボックスを表示したい場合はどうでしょうか。ビューモデルは何にバインドし、メッセージボックスの作成/表示をどのようにトリガーしますか?

4

2 に答える 2

27

次のようなインターフェースを使用IMessageBoxServiceします。

interface IMessageBoxService
{
    bool ShowMessage(string text, string caption, MessageType messageType);
}

WPFMessageBoxServiceクラスを作成します。

using System.Windows;

class WPFMessageBoxService : IMessageBoxService
{
    bool ShowMessage(string text, string caption, MessageType messageType)
    {
        // TODO: Choose MessageBoxButton and MessageBoxImage based on MessageType received
        MessageBox.Show(text, caption, MessageBoxButton.OK, MessageBoxImage.Information);
    }
}

ViewModelコンストラクターパラメーターとしてIMessageBoxServiceを受け入れ、DI/IoCを使用して注入しWPFMessageBoxServiceます。

ViewModelで、を使用IMessageBoxService.ShowMessageしてメッセージボックスを表示します。

ShowMessageCommand = new DelegateCommand (
    () => messageBoxService.ShowMessage(message, header, MessageType.Information)
);

IMessageBoxService必要に応じてインターフェースをカスタマイズし、より適切な名前を選択してください。

于 2013-01-12T20:27:11.447 に答える
2

メッセージボックスコントロールの可視性を検証にバインドできます。

このためには、BoolToVisibilityコンバーターが必要になります。

組み込みのコンバーターの使用については、こちらを参照してください: ViewModelのbool値にボタンの可視性をバインドする

于 2013-01-12T20:01:50.967 に答える