基本は xaml で CommandParameter属性 を指定することで引数を渡せます。 以下ではいくつかの サンプルコード を記載しました。
目次
- 固定値 を 渡す 例
- 要素 を 渡す 例
- コントロールを渡す例
- Windowを渡す例
- 要素 の プロパティ を 渡す 例
固定値 を 渡す 例
CommandParameter="固定値" を指定します。 ラジオボタンくらいしか使い道が思いつきません…。
<Window x:Class="WpfApplication.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfApplication.ViewModels"
Title="MainWindow"
Name="window" >
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<RadioButton Content="春"
Command="SelectSeason"
CommandParameter="1" />
<RadioButton Content="夏"
Command="SelectSeason"
CommandParameter="2" />
<RadioButton Content="秋"
Command="SelectSeason"
CommandParameter="3" />
<RadioButton Content="冬"
Command="SelectSeason"
CommandParameter="4" />
</Grid>
</Window>
要素 を 渡す 例
渡したい要素に Name属性 を設定し、CommandParameter="{Binding ElementName=要素名}" を指定します。 Name属性 さえ指定していれば良いので、 Control でも Window でも渡せてしまいます。
TextBox コントロール を引数に渡す 例
<Window x:Class="WpfApplication.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfApplication.ViewModels"
Title="MainWindow"
Name="window" >
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<TextBox Text="サンプル"
Name="textbox" />
<Button Content="閉じる"
Command="Close"
CommandParameter="{Binding ElementName=textbox}"/>
</Grid>
</Window>
Window を引数に渡す 例
<Window x:Class="WpfApplication.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfApplication.ViewModels"
Title="MainWindow"
Name="window" >
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<TextBox Text="サンプル"
Name="textbox" />
<Button Content="閉じる"
Command="Close"
CommandParameter="{Binding ElementName=window}"/>
<!-- CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}} -->
</Grid>
</Window>
要素 の プロパティ を 渡す 例
渡したい要素に Name属性 を設定し、CommandParameter="{Binding ElementName=要素名 Path=プロパティ名}" を指定します。
TextBox の Textプロパティ を引数に渡す 例
<Window x:Class="WpfApplication.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfApplication.ViewModels"
Title="MainWindow"
Name="window" >
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<TextBox Text="サンプル"
Name="textbox" />
<Button Content="閉じる"
Command="Close"
CommandParameter="{Binding ElementName=textbox Path=Text}"/>
</Grid>
</Window>
最後に… このブログに興味を持っていただけた方は、 ぜひ 「Facebookページ に いいね!」または 「Twitter の フォロー」 お願いします!!