[英]How to get a child of an “object sender” in a method?
I have a 15 borders with an image inside of it in my application that calls a method on MouseUp.. all images have different names.. hence why i want them all to call this one method 我的应用程序中有一个带有15个边框的图像,它在MouseUp上调用一个方法..所有图像都有不同的名称..因此为什么我希望它们都调用这个方法
<GroupBox Width="75" Height="75">
<Border MouseLeftButtonUp="Image_MouseUp1" Background="Transparent">
<Image x:Name="RedPick5_Image" Height="Auto" Width="Auto"/>
</Border>
</GroupBox>
I want all of them to be able to set the image source of the child (the image is the child of the border if i understand correctly.. how can i do this? 我希望他们所有人都能够设置孩子的图像源(如果我理解正确,图像就是边框的孩子..我怎么能这样做?
private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
{
//want to set any image that calls this
//something like Sender.Child.Source = ...
}
you need to cast the sender and check 你需要施放发件人并检查
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
}
you could also do this 你也可以这样做
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
}
You can do this way in case image is only and immediate child of border: 如果图像只是边框的直接子节点,你可以这样做:
Image image = (Image)((Border)sender).Child;
image.Source = // Set image source here.
Alternatively you can use FindName
或者,您可以使用
FindName
(Image)(sender as Border).FindName("RedPick5_Image");
It will search Border
's children recursively for an element named "RedPick5_Image". 它将以递归方式搜索
Border
的子节点,以获取名为“RedPick5_Image”的元素。 This may return null if no elements with the specified name is found. 如果未找到具有指定名称的元素,则此参数可能返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.