Answer the question
In order to leave comments, you need to log in
How to move an object in C# WPF?
I'm trying to make a simple application, but I just can't figure out how to move objects (images).
I do it like this:
XAML:
<Canvas x:Name="main" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Image Height="767" Canvas.Top="0" Width="1365" x:Name="Ground" Source="images/land.jpg" Stretch="UniformToFill" Canvas.Left="0"/>
</Canvas>
enum CellType { Empty, Visited, Sun };
CellType[,] Board = new CellType[41, 41];
public MainPage()
{
this.InitializeComponent();
SetupSuns();
timerStart();
}
public int x = 31;
public int y = 4;
public void SetupSuns()
{
var ninja = new Image();
ninja.Source = new BitmapImage(new Uri("ms-appx:/images/ninjarun.png"));
if (x == 31)
{
ninja.Source = new BitmapImage(new Uri("ms-appx:/images/ninjarun2.png"));
}
ninja.Width = 32;
ninja.Height = 39;
Board[x, y] = CellType.Sun;
main.Children.Add(ninja);
Canvas.SetLeft(ninja, x * 40);
Canvas.SetTop(ninja, y * 40);
}
private DispatcherTimer timer = null;
private void timerStart()
{
timer = new DispatcherTimer(); // если надо, то в скобках указываем приоритет, например DispatcherPriority.Render
timer.Tick += (sender, e) =>
{
x++;
Canvas.SetLeft(ninja, x * 40);
if (x == 50)
{
timer.Stop();
}
};
timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
timer.Start();
}
}
Answer the question
In order to leave comments, you need to log in
Instead of a timer, use animation. In this case, DoubleAnimation or DoubleAnimationUsingKeyFrames . It is not the x property that needs to be changed, but Canvas.Left; you can use transform , it works in other containers too.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question