Changing an image location in WPF
15,434
Solution 1
Here's an example:
<Canvas x:Name="canvas">
<Rectangle x:Name="rect" Width="20" Height="20" Canvas.Left="10" Canvas.Top="10" Fill="Blue" MouseEnter="RectangleMouseEnter" />
</Canvas>
You need to set the attached properties top, left (or bottom, right)
private void RectangleMouseEnter(object sender, MouseEventArgs e)
{
Canvas.SetTop(rect, 50);
Canvas.SetLeft(rect, 50);
}
Solution 2
In order to set position of the Image on the Canvas from code-behind you can use something like:
private void cat_MouseEnter(object sender, MouseEventArgs e)
{
Canvas.SetLeft(cat, 100); //set x coordinate of cat Image to 100
Canvas.SetTop(cat, 300); //set y coordinate of cat Image to 300
}
Update:
In some cases you may not be able to access cat
object by name from that method. In order to make it work, just use the sender object that should be the Image
that caused the event, as H.B. described in his comment.
Author by
Josh
Updated on June 04, 2022Comments
-
Josh almost 2 years
I am trying to have the location of an image change when I mouseover. I have:
<Image Name="cat" Source="CatRun.bmp" Visibility="Hidden" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100" UIElement.MouseEnter="cat_MouseEnter"/>
in XAML and:
private void cat_MouseEnter(object sender, MouseEventArgs e) { }
in C#.
How can I set the location specifically on the canvas?
-
H.B. over 12 yearsvar image = (Image)sender; Canvas.SetLeft(image, 42);
-
-
Lukasz M over 12 yearsYes, you are right, it won't compile then. I'll update the answer with some more info.