MVVMではCommandバインド(二)伝達Commandパラメータを容易に実現


Commandでパラメータを渡す必要がある場合は、実装も簡単です.DelegateCommandには、Tタイプのパラメータを渡すDelegateCommandバージョンもあります.
1.CommandParameterが「20」のパラメータを定義した、ViewのButtonバインド
<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:vm="clr-namespace:WpfApplication1"
        Title="Window1" Height="193" Width="190">
	<Window.DataContext>
		<vm:Window1ViewModel />
	</Window.DataContext>
    <Grid>
		<Button Content="Button" Height="33" HorizontalAlignment="Left" Margin="34,20,0,0" Name="button1" VerticalAlignment="Top" Width="109"
				Command="{Binding ButtonCommand}"
				CommandParameter="20"/>
	</Grid>
</Window>

2.ViewModel定義コマンド、注意依頼パラメータ
namespace WpfApplication1 {
	public class Window1ViewModel {

		public ICommand ButtonCommand {
			get {
				return new DelegateCommand<string>((str) => {
					MessageBox.Show("Button's parameter:"+str);
				});
			}
		}

	}
}

また,特別な場合には,コントロールオブジェクトをパラメータとしてViewModelに渡すことができ,{Binding RelativeSource={x:Static RelativeSource.Self}}は自分自身(Button)をバインドするという意味であることに注意する.
<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:vm="clr-namespace:WpfApplication1"
        Title="Window1" Height="193" Width="190">
	<Window.DataContext>
		<vm:Window1ViewModel />
	</Window.DataContext>
    <Grid>
		<Button Content="Button" Height="33" HorizontalAlignment="Left" Margin="34,20,0,0" Name="button1" VerticalAlignment="Top" Width="109"
				Command="{Binding ButtonCommand}"
				CommandParameter="20"/>
		<Button Content="Button" Height="33" HorizontalAlignment="Left" Margin="34,85,0,0" Name="button2" VerticalAlignment="Top" Width="109"
				Command="{Binding ButtonCommand2}"
				CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"/>
	</Grid>
</Window>

ビューモデルを見て
namespace WpfApplication1 {
	public class Window1ViewModel {

		public ICommand ButtonCommand {
			get {
				return new DelegateCommand<string>((str) => {
					MessageBox.Show("Button's parameter:"+str);
				});
			}
		}

		public ICommand ButtonCommand2 {
			get {
				return new DelegateCommand<Button>((button) => {
					button.Content = "Clicked";
					MessageBox.Show("Button");
				});
			}
		}
	}
}

これで依頼中にButtonオブジェクトを取得できます.ただしMVVM自体は、ViewModelよりもViewを操作することを推奨している.
次回は、さまざまなイベントのViewModelトリガに使用できるより強力なコマンドバインドについて説明します.じゃ、また今度!