解密哪个控件发起了一个事件

时间:2010-05-19 20:03:59

标签: c# .net wpf xaml event-handling

我有一个包含许多图像的应用程序,它们看起来都一样,并执行类似的任务:

<Image Grid.Column="1" Grid.Row="0" Name="image_prog1_slot0" Stretch="Uniform" Source="bullet-icon.png" StretchDirection="Both" MouseDown="image_prog1_slot0_MouseDown"/>
            <Image Grid.Column="1" Grid.Row="1" Name="image_prog1_slot1" Stretch="Uniform" Source="bullet-icon.png" StretchDirection="Both" />
            <Image Grid.Column="1" Grid.Row="2" Name="image_prog1_slot2" Stretch="Uniform" Source="bullet-icon.png" StretchDirection="Both" />

现在,我想将每个链接到同一个事件处理程序:

private void image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //this_program = ???;
            //this_slot = ???;
            //slots[this_program][this_slot] = some value;
        }

显然,图像的程序编号和插槽编号是其名称的一部分。有没有办法在触发事件处理程序时提取此信息?

1 个答案:

答案 0 :(得分:6)

是的,这是可能的。

顾名思义,sender参数包含触发事件的对象。

您还可以使用Grid附加的属性来确定它所在的行和列。(也可以通过这种方式获取其他附加属性。)

private void image_MouseDown(object sender, MouseButtonEventArgs e)
{
    // Getting the Image instance which fired the event
    Image image = (Image)sender;

    string name = image.Name;
    int row = Grid.GetRow(image);
    int column = Grid.GetRow(image);

    // Do something with it
    ...
}

旁注:

您还可以使用Tag属性存储有关控件的自定义信息。 (它可以存储任何对象。)