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
<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
(Image)(sender as Border).FindName("RedPick5_Image");
It will search Border
's children recursively for an element named "RedPick5_Image". This may return null if no elements with the specified name is found.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.