我有一个包含许多图像的应用程序,这些图像看起来都一样并且执行类似的任务:
<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;
}
很明显,图像的程序编号和插槽编号是其名称的一部分。有没有办法在触发事件处理程序时提取此信息?
最佳答案
是的,这是可能的。
顾名思义,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
属性来存储有关控件的自定义信息。 (它可以存储任何对象。)
关于c# - 破译触发事件的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868977/