我的应用程序中有一个15个边框,里面有一个图像,它在MouseUp上调用一个方法..所有图像都有不同的名称..因此为什么我希望它们都能称之为一个方法
<GroupBox Width="75" Height="75">
<Border MouseLeftButtonUp="Image_MouseUp1" Background="Transparent">
<Image x:Name="RedPick5_Image" Height="Auto" Width="Auto"/>
</Border>
</GroupBox>
我希望他们所有人能够设置孩子的图像源(如果我理解正确,图像就是边框的孩子..我该怎么做?
private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
{
//want to set any image that calls this
//something like Sender.Child.Source = ...
}
答案 0 :(得分:3)
您需要投射发件人并检查
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
}
你也可以这样做
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
}
答案 1 :(得分:2)
你可以这样做,以防图像只是边框的直接子项:
Image image = (Image)((Border)sender).Child;
image.Source = // Set image source here.
答案 2 :(得分:1)
或者您可以使用FindName
(Image)(sender as Border).FindName("RedPick5_Image");
它将以递归方式搜索Border
个孩子的名为“RedPick5_Image”的元素。如果没有找到具有指定名称的元素,则可能返回null。