在WPF中按下了哪个按钮?

时间:2013-01-24 23:57:18

标签: c# wpf image list button

我得到了这些代码:

在cs:

一类get {和ImgSmallNameImgLarge

List<Img> sectionList = new List<Img> 
{ 
  new Img
  {
      ImgSmall="Img/NG.png", Name="New Game", ImgLarge="Img/NG.png"
  },

  new Img
  {
      ImgSmall="Img/HS.png", Name="High Score", ImgLarge="Img/HS.png"
  },
}

在XAML(适用于Images/Buttons的样式模板)中:

<Button BorderThickness="0" Click="Button_Click_1" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}">
    <Image x:Name="image" Width="64" Height="64" Source="{Binding ImgSmall}" />
</Button>

当我创建超过Button时,如何查看哪个1 Button被按下?我的猜测是检查传递对象的名称,但我真的不知道。

点击方法:

private void Button_Click_1(object sender, RoutedEventArgs e)
{

}

1 个答案:

答案 0 :(得分:4)

在这种情况下,您可以使用非常有用的内容:属性Tag。您使用绑定在XAML中设置Tag,然后检查其值。

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    FrameworkElement frameworkElement = sender as FrameworkElement;
    if(sender != null)
    {
        Img tag = frameworkElement.Tag as Img;

        // You directly have the Img that correspond to the button you have clicked
    }
}

在XAML中:

<Button BorderThickness="0" Click="Button_Click_1" Tag="{Binding}" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" >
    <Image x:Name="image" Width="64" Height="64" Source="{Binding ImgSmall}"/>
</Button>