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