Prism コードサンプル学習:29-InvokeCommandAction
はじめに
以下の記事の続きです。
https://qiita.com/mngreen/items/0e0e41705b4f53d45360
29-InvokeCommandAction
本サンプルは、Itemの一覧を表示するビューが表示されるサンプルになっており、その一覧の要素を選択するとウインドウ下部のテキストブロックが書き換わります。
この書き換える処理の実装にPrismのInvokeCommandActionが利用されています。
<Window ... >
<Grid>
...
<ListBox Grid.Row="1" Margin="5" ItemsSource="{Binding Items}" SelectionMode="Single">
<i:Interaction.Triggers>
<!-- This event trigger will execute the action when the corresponding event is raised by the ListBox. -->
<i:EventTrigger EventName="SelectionChanged">
<!-- This action will invoke the selected command in the view model and pass the parameters of the event to it. -->
<prism:InvokeCommandAction Command="{Binding SelectedCommand}" TriggerParameterPath="AddedItems" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
...
</Grid>
</Window>
上記でバインディングされているコマンドはVMで定義されています。
また、TriggerParameterPathで指定されている"AddedItems"はSelectionChangedイベントが発行したときのSelectionChangedEventArgs引数の中のAddedItemsプロパティを利用するという宣言になります。
VMは以下の処理となっています。
...
namespace UsingInvokeCommandAction.ViewModels
{
public class MainWindowViewModel : BindableBase
{
...
private string _selectedItemText;
public string SelectedItemText
{
get { return _selectedItemText; }
private set { SetProperty(ref _selectedItemText, value); }
}
public IList<string> Items { get; private set; }
public DelegateCommand<object[]> SelectedCommand { get; private set; }
public MainWindowViewModel()
{
Items = new List<string>();
Items.Add("Item1");
Items.Add("Item2");
Items.Add("Item3");
Items.Add("Item4");
Items.Add("Item5");
// This command will be executed when the selection of the ListBox in the view changes.
SelectedCommand = new DelegateCommand<object[]>(OnItemSelected);
}
private void OnItemSelected(object[] selectedItems)
{
if (selectedItems != null && selectedItems.Count() > 0)
{
SelectedItemText = selectedItems.FirstOrDefault().ToString();
}
}
}
}
上記の中で、MainWindowViewModel.OnItemSelectedメソッドがSelectedCommandの実処理となりますが、このときの引数であるselectedItemsパラメーターにさきほど示したAddedItemsプロパティが入るという関係性になっています。
ここではInvokeCommandActionの実装を読み進め、どのようにプロパティを取得しているか見ていきます。
読み進めると、Invokeメソッド内の処理でリフレクションを利用してプロパティを取得していました。
"."で分割してループしているため、イベント引数が入れ子になっていた場合があったとしても問題ない実装になっています。
もし値が取得できればコマンド実行時にパラメーターとして渡され、上記の振る舞いが実現されているようです。
おわりに
今回は29-InvokeCommandActionクラスを読み進め、どのようにイベント引数とコマンドのパラメーターをつなげているのかを読み進めました。
リフレクションをうまく活用する、という点で勉強になりました。
WPFのサンプルは本サンプルですべて読み終わったため、他のリポジトリを読んだり、気になるところがあればまた取り上げて見ていこうと思います。