W
W
wolfak2014-03-09 18:29:41
WPF
wolfak, 2014-03-09 18:29:41

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>

C#:
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();
        }
    }

I'm just learning how to write applications in C#, so I need your help.
It is necessary that the created ninja image is moved using a timer along the x-axis variable.
Which is currently not working.
Also wondering how you can solve the same problem with several similar moving objects? How to access a ninja object from one class to another and change its property(x)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Vishnyakov, 2014-03-09
@wolfak

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 question

Ask a Question

731 491 924 answers to any question