xamlに定義したButtonのCommandParameterをイベントハンドラで受け取る
たとえばこんなItemsSourceとイベントの定義がある時
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="300" Width="300"
x:Class="Boo.FooWindow">
<Grid>
<DataGrid x:Name="HogeDG" IsReadOnly="True" AutoGenerateColumns="False">
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTemplateColumn Header="Action">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Action" CommandParameter="{Binding ID}" Click="HogeClick"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid>
</Grid>
</Window>
namespace Boo {
public class FooWindow : Window {
public FooWindow() {
this.HogeDG.ItemsSource = new List() {
new Hoge() { ID = 1, Name = "Bar" }
, new Hoge() { ID = 2, Name = "Baz" }
};
}
private void HogeClick(object sender, RoutedEventArgs e) {
// クリックされたHogeのIDを表示したい
}
}
}
今回の目標は、クリックされた行のHogeのIDをConsole.WriteLine
することです。
しかしCommandParameter
はICommand
のExecute(object parameter)
に渡されるものなので
普通のイベントハンドラであるHogeClick
では受け取れません。
そんな場合はこうしてやると、ICommand#Execute
同様に受け取れます。
namespace Boo {
public class FooWindow : Window {
public FooWindow() {
this.HogeDG.ItemsSource = new List() {
new Hoge() { ID = 1, Name = "Bar" }
, new Hoge() { ID = 2, Name = "Baz" }
};
}
private void HogeClick(object sender, RoutedEventArgs e) {
// クリックされたHogeのIDを表示したい
int id = (int)((Button)sender).CommandParameter;
Console.WriteLine(id);
}
}
}