複数のボタンに同じコマンドを定義
MainWindow.xaml
<StackPanel Width="60">
<StackPanel.Resources> ①
<Style TargetType="Button"> ②
<Setter Property="Command" Value="{Binding cm}"/> ③
</Style>
</StackPanel.Resources>
<Button Content="aa"/> ④
<Button Content="ii"/>
</StackPanel>
①今からオブジェクトリソースを書くぞという宣言
②これから書くボタンはみんなこのスタイルを適用するぞという宣言
③実際のスタイル Propertyでプロパティ名を指定 Valueで値を指定
④実際のボタン
MainWindow.xaml.cs
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
cm = new comand();
}
public ICommand cm{get;set;}
}
public class comand : ICommand
{
// 概要:
// コマンドを実行するかどうかに影響するような変更があった場合に発生します。
public event EventHandler CanExecuteChanged;
// 概要:
// 現在の状態でこのコマンドを実行できるかどうかを判断するメソッドを定義します。
//
// パラメーター:
// parameter:
// コマンドで使用されたデータ。 コマンドにデータを渡す必要がない場合は、このオブジェクトを null に設定できます。
//
// 戻り値:
// このコマンドを実行できる場合は true。それ以外の場合は false。
public bool CanExecute(object parameter)
{ return true; }
//
// 概要:
// コマンドの起動時に呼び出されるメソッドを定義します。
//
// パラメーター:
// parameter:
// コマンドで使用されたデータ。 コマンドにデータを渡す必要がない場合は、このオブジェクトを null に設定できます。
public void Execute(object parameter)
{
System.Windows.Forms.MessageBox.Show("hello");
}
}
}
説明略。
参考:
http://www.atmarkit.co.jp/ait/articles/1009/07/news096_2.html