はじめに
こちらの記事は以下記事の改良版です。
ダイアログのタイトル・テキスト設定する部分が不格好なので改善の余地ありですが…。
ここの不格好、もっさり感を改善しました。
環境
- .NET 5.0
- C#
- Prism.Unity
- MaterialDesignThemes
ダイアログView
MyMessageBox.xaml
変更なし
MyMessageBox.xaml.sc
using MaterialDesignThemes.Wpf;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace TestApp.Views
{
public partial class MyMessageBox : UserControl
{
public MyMessageBox()
{
InitializeComponent();
}
public static Task<object?> Show(string text, string caption)
{
var dialog = new MyMessageBox();
dialog.DataContext = new { DialogTitle = caption, DialogText = text };
return DialogHost.Show(dialog);
}
}
}
xaml.scファイルにstaticで呼び出せるShow()
メソッドを追加しました。
ここでDataContextを設定してやることで、
課題であった不格好さ、呼び出し元ViewModelでのプロパティ追加不要等改善されました。
ダイアログを表示させるViewとViewModel
ManWindow.xaml
変更なし
MainWindowViewModel.cs
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;
using System.Diagnostics;
using TestApp.Views;
namespace TestApp.ViewModels
{
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel()
{
}
// プロパティ
private string _title = "MessageBoxApplication";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
-
- private string _dialogTitle;
- public string DialogTitle
- {
- get { return _dialogTitle; }
- set { SetProperty(ref _dialogTitle, value); }
- }
-
- private string _dialogText;
- public string DialogText
- {
- get { return _dialogText; }
- set { SetProperty(ref _dialogText, value); }
- }
// コマンド
private DelegateCommand<string> _clickCommand;
public DelegateCommand<string> ClickCommand =>
_clickCommand ?? (_clickCommand = new DelegateCommand<string>(ExecuteCommandName));
// コマンド実行メソッド
private async void ExecuteCommandName(string parameter)
{
- DialogTitle = "確認";
- DialogText = "ダイアログの説明文です。よろしいですか?";
- var result = await DialogHost.Show(new MyMessageBox());
+ var result = await MyMessageBox.Show("ダイアログの説明文です。よろしいですか?", "確認");
if ((string)result == "OK")
{
Debug.Print("OKが押されました。");
}
else if ((string)result == "キャンセル")
{
Debug.Print("キャンセルが押されました。");
}
else
{
Debug.Print("ダイアログの外が押されました。");
}
}
}
}
以上のようにだいぶすっきりし、かつ以前より更にSystem.Windows.Forms
のMessageBox.Show()
ライクに近づきました。
Show()
の引数を増やして、Viewのデザインやアイコンの有無、ボタンを変更できるようにすれば、
更にMessageBox.Show()
のように使うことができるのではないでしょうか。
【おまけ】DialogHostを複数扱う場合
ManWindow.xaml
- <materialDesign:DialogHost CloseOnClickAway="True" DialogTheme="Inherit">
+ <materialDesign:DialogHost CloseOnClickAway="True" DialogTheme="Inherit" Identifier="DialogA">
MyMessageBox.xaml.sc
- return DialogHost.Show(dialog);
+ return DialogHost.Show(dialog, "DialogA");
DialogHostを複数扱う場合はViewのDialogHostのIdentifier
を設定し、
DialogHost.Show
の第二引数に同じ識別子を設定してください。