解读哪个控件触发了事件

3

我有一个应用程序,其中有许多看起来相同且执行类似任务的图像:

<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个回答

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属性存储有关控件的自定义信息。 (它可以存储任何对象。)


+1. 也可以将“sender”与每个成员变量进行比较,以确定它是哪个控件。 - Isak Savo
谢谢!是的,那也是可能的。 - Venemo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接