WPFとLivetでhelloworldを作ってみた (2)
前回の記事「WPFとLivetでhelloworldを作ってみた - Unity 勉強メモ」 ではボタンを押すとテキストボックスに"Hello, World."と表示するプログラムを 作りました。 今回は、ボタンをクリックするとテキストボックスの内容をメッセージボックスに 表示するプログラムを作りたいと思います。
見た目の構築
Visual Studio で「Livet WPF4.5 MVVM アプリケーション」を新規に作成します。 ここではプロジェクト名を「LivetHelloWorld2」としました。
MainWindow.xaml
を開いて、<Grid></Grid>
の部分を以下のように書き換えます。
<StackPanel Margin="10"> <TextBox Margin="10"/> <Button Margin="10" Content="表示"/> </StackPanel>
コマンドとプロパティをViewModelに作成
MainWindowViewModel.cs
を開いて、以下のコードを追加します。
#region ShowCommand private ViewModelCommand _ShowCommand; public ViewModelCommand ShowCommand { get { if (_ShowCommand == null) { _ShowCommand = new ViewModelCommand(Show); } return _ShowCommand; } } public void Show() { } #endregion #region TextBoxText変更通知プロパティ private string _TextBoxText; public string TextBoxText { get { return _TextBoxText; } set { if (_TextBoxText == value) return; _TextBoxText = value; RaisePropertyChanged(); } } #endregion
MainWindow.xaml
を開いて、
InteractionMessageTrigger
の追加
MainWindow.xaml
の<i:Interaction.Triggers>...</i:Interaction.Triggers>
の間に以下のコードを追加します。
<l:InteractionMessageTrigger Messenger="{Binding Messenger}" MessageKey="ShowMessage"> <l:ConfirmationDialogInteractionMessageAction/> </l:InteractionMessageTrigger>
Show()
メソッドの実装
MainWindowViewModel.cs
を開いて、Show()
メソッドの中身に以下のようにコードを記述します。
public void Show() { Messenger.Raise(new ConfirmationMessage(TextBoxText, "情報", "ShowMessage")); }
別の実装方法
書きながら気づいたのですが、以下のように記述することもできますね。
<StackPanel Margin="10"> <TextBox Margin="10" Text="{Binding Path=TextBoxText}"/> <Button Margin="10" Content="表示"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <l:ConfirmationDialogInteractionMessageAction> <l:DirectInteractionMessage> <l:ConfirmationMessage Text="{Binding Path=TextBoxText}"/> </l:DirectInteractionMessage> </l:ConfirmationDialogInteractionMessageAction> </i:EventTrigger> </i:Interaction.Triggers> </Button> </StackPanel>