Livetを使ってViewModelからMessageBox表示
ViewModelから直接MessageBox.Showを実行しても動きますが、ViewModelからコントロールを直接制御しないというのが理想なので、ViewModelからメッセージを送る形でMessageBoxを表示させます。
Livetを使用する場合は、比較的簡単に実装できます。
この実装が完全に正しいかどうかは正直よく分かっていませんが、まぁ動きます。
実装する量としては結局のところMessageBox.Showと変わりません。ただ面倒なだけです。
と考えるのは浅はかなのか。。。。
▼XAML
<i:Interaction.Triggers> <l:InteractionMessageTrigger Messenger="{Binding Messenger}" MessageKey="Information"> <l:InformationDialogInteractionMessageAction/> </l:InteractionMessageTrigger> <l:InteractionMessageTrigger Messenger="{Binding Messenger}" MessageKey="Confirm"> <l:ConfirmationDialogInteractionMessageAction /> </l:InteractionMessageTrigger> <l:InteractionMessageTrigger Messenger="{Binding Messenger}" MessageKey="Error"> <l:InformationDialogInteractionMessageAction/> </l:InteractionMessageTrigger> </i:Interaction.Triggers>
▼ViewModel
ViewModelのベースクラスに実装しておくと便利
/// <summary> /// 情報ダイアログを表示する /// 使用するにはView側に、InteractionMessageTriggerの定義が必要 /// <param name="message"></param> /// <param name="title"></param> public void ShowInfoDialog(string message, string title = "情報") { Messenger.Raise(new InformationMessage(message, title, MessageBoxImage.Information, "Information")); } /// <summary> /// エラーダイアログを表示する /// 使用するにはView側に、InteractionMessageTriggerの定義が必要 /// </summary> /// <param name="message"></param> /// <param name="title"></param> public void ShowErrorDialog(string message, string title = "エラー") { Messenger.Raise(new InformationMessage(message, title, MessageBoxImage.Error, "Error")); } /// <summary> /// 確認ダイアログを表示する /// 使用するにはView側に、InteractionMessageTriggerの定義が必要 /// <param name="message"></param> /// <param name="title"></param> /// <returns>OKが押された場合はtrue</returns> public bool ShowConfirmDialog(string message, string title = "確認") { var confirmationMessage = new ConfirmationMessage(message, title, MessageBoxImage.Question, MessageBoxButton.OKCancel, "Confirm"); Messenger.Raise(confirmationMessage); return confirmationMessage.Response ?? false; } // 必要なタイミングで呼べばよい ShowInfoDialog("処理完了"); ShowErrorDialog("エラー発生"); if (ShowConfirmDialog("処理を実行しますか?")) { // OKが押されたときの処理 }
== ランキングに参加しています。ぜひクリックお願いします ==