for WPF developers
メッセージダイアログです。
ページ内リンク
MessageBox コントロールは、メッセージを表示し、それに対するユーザのレスポンスを取得するダイアログです。したがって、ビヘイビアなどでよく使われます。
MessageBox コントロールを使用したサンプルコードを以下に示します。
理想的な MVVM パターンでは、ViewModel から View を呼び出すことはマナー違反ですが、
簡単なメッセージを出力するのに一々複雑なビヘイビアなどを作成することは煩わしいため、
サンプルコードのように ViewModel から直接 MessageBox コントロールを呼び出すこともあります。
<YK:Window x:Class="Section4_9.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:YK="clr-namespace:YKToolkit.Controls;assembly=YKToolkit.Controls"
Title="MainView" Height="300" Width="300">
<StackPanel>
<Button Content="Ok or Cancel" Command="{Binding OkCancelCommand}" />
<TextBlock Text="{Binding OkCancelText}" />
<Button Content="Yes, No or Cancel" Command="{Binding YesNoCancelCommand}" />
<TextBlock Text="{Binding YesNoCancelText}" />
</StackPanel>
</YK:Window>
namespace Section4_9.ViewModels
{
using YKToolkit.Bindings;
using YKToolkit.Controls;
public class MainViewModel : NotificationObject
{
private string okCancelText;
/// <summary>
/// OkCancel メッセージボックスの結果を取得します。
/// </summary>
public string OkCancelText
{
get { return okCancelText ?? "null"; }
private set { SetProperty(ref okCancelText, value); }
}
private string yesNoCancelText;
/// <summary>
/// YesNoCancel メッセージボックスの結果を取得します。
/// </summary>
public string YesNoCancelText
{
get { return yesNoCancelText ?? "null"; }
private set { SetProperty(ref yesNoCancelText, value); }
}
private DelegateCommand okCancelCommand;
/// <summary>
/// Ok/Cancel メッセージボックス表示コマンドを取得します。
/// </summary>
public DelegateCommand OkCancelCommand
{
get
{
return okCancelCommand ?? (okCancelCommand = new DelegateCommand(_ =>
{
// ViewModel から Window クラスを呼び出すのは
// MVVM 的にはあまり美しいコードではないが
// 現実的にはこれが一番楽
var result = MessageBox.Show("こんにちは。", "OK か Cancel", MessageBoxButton.OKCancel, MessageBoxImage.Question);
OkCancelText = result.ToString();
}));
}
}
private DelegateCommand yesNoCancelCommand;
/// <summary>
/// Yes/No/Cancel メッセージボックス表示コマンドを取得します。
/// </summary>
public DelegateCommand YesNoCancelCommand
{
get
{
return yesNoCancelCommand ?? (yesNoCancelCommand = new DelegateCommand(_ =>
{
// ViewModel から Window クラスを呼び出すのは
// MVVM 的にはあまり美しいコードではないが
// 現実的にはこれが一番楽
var result = MessageBox.Show("さようなら。", "Yes か No か Cancel", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
YesNoCancelText = result.ToString();
}));
}
}
}
}
MessageBox クラスには Show() 静的メソッドがあるため、これを使用してダイアログを表示します。
また、結果として YKToolkit.Controls.MessageBoxResult 列挙体が返ってくるため、これを判定して次の処理につなげることができます。
サンプルコードでは返ってきた結果をそのまま string 型に変換して表示しています。
Designed by CSS.Design Sample