如何在方法中获取“对象发送者”的子对象?

use*_*352 3 c# wpf

我的应用程序中有 15 个边框,其中有一个图像,它调用 MouseUp 上的一个方法。所有图像都有不同的名称。因此,为什么我希望它们都调用这个方法

<GroupBox Width="75" Height="75">
      <Border MouseLeftButtonUp="Image_MouseUp1" Background="Transparent">
           <Image x:Name="RedPick5_Image" Height="Auto" Width="Auto"/>
      </Border>
</GroupBox>
Run Code Online (Sandbox Code Playgroud)

我希望他们所有人都能够设置子项的图像源(如果我理解正确的话,图像是边框的子项..我该怎么做?

        private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
        {
            //want to set any image that calls this
            //something like Sender.Child.Source = ...
        }
Run Code Online (Sandbox Code Playgroud)

Wii*_*axx 5

您需要投射发件人并检查

    private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
    {
        var border = sender as Border; // Cast to Border
        if (border != null)            // Check if the cast was right
        {
            var img = border.Child as Image;  // Cast to Image
            if (img != null)                  // Check if the cast was right
            {
                // your code
            }
            // else your Child isn't an Image her you could hast it to an other type
        }
        // else your Sender isn't an Border
    }
Run Code Online (Sandbox Code Playgroud)

你也可以这样做

    private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
    {
        var border = sender as Border;
        if (border == null) // if the cast to Border failed
            return;         

        var img = border.Child as Image;
        if (img == null) // if the cast to Image failed
            return;

        // your code
    }
Run Code Online (Sandbox Code Playgroud)