Deciphering which control fired an event

点点圈 提交于 2021-01-27 12:39:38

问题


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?


回答1:


Yes, it is possible.

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

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
    ...
}

Side note:

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



来源:https://stackoverflow.com/questions/2868977/deciphering-which-control-fired-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!