解密哪个控件触发了一个事件 [英] Deciphering which control fired an event

查看:56
本文介绍了解密哪个控件触发了一个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多图像的应用程序,这些图像看起来都相同并且执行相似的任务:

I have an application with many images that all look the same and perform similar tasks:

<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" />

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

Now, I want to link each one to the same event handler:

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

很明显,映像的程序号和插槽号是其名称的一部分.触发事件处理程序时,是否有一种方法可以提取此信息?

Obviously the program number and slot number of the image are part of its name. Is there a way to extract this information when the event handler is fired?

推荐答案

是的,有可能.

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

As its name suggests, the sender parameter contains the object which fired the event.

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

You can also use the Grid's attached properties for convenience to determine which row and column it is in. (It is also possible to get other attached properties this way.)

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

You can also use the Tag property to store custom information about controls. (It can store any objects.)

这篇关于解密哪个控件触发了一个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆