c# - 破译触发事件的控件

标签 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;
        }

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

最佳答案

是的,这是可能的。

顾名思义,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/

相关文章:

.net - 从第 3 方源恢复 NuGet 包

c# - 如何使用多参数linq从数据库中获取记录

c# - 在WPF应用程序中找不到Startupuri

wpf - WPF DataGrid计算的总计列

c# - 使用 XAML 中的通用 IValueConverter

c# - Entity Framework 使用单个查询进行多次计数

c# - 如何使用Azure Functions将数据发送到服务总线主题?

.net - 在新 XmlElement 上设置 InnerXml 后空白 xmlns =""

c# - 如何在 wpf 应用程序中创建键盘输入?

c# - 安装Azure SDK 2.5后如何运行Azure 2.2项目