5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

xamlに定義したButtonのCommandParameterをイベントハンドラで受け取る

Posted at

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することです。
しかしCommandParameterICommandExecute(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);
    }
  }
}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?