【问题标题】:Deciphering which control fired an event破译哪个控件触发了一个事件
【发布时间】:2026-01-19 02:05:01
【问题描述】:

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

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

显然,图像的程序号和槽号是其名称的一部分。有没有办法在事件处理程序被触发时提取这些信息?

【问题讨论】:

    标签: c# .net wpf xaml event-handling


    【解决方案1】:

    是的,有可能。

    顾名思义,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' 与每个成员变量进行比较,以查看它是哪个控件
    • 谢谢!是的,这也是可能的。
    最近更新 更多