
How to make the item move on the page?
Run Visual studio 2008 sp1 edition
New project--->WPF Project.
On Window1.xaml
Only put a Canvas here called Carrier
〈 Window x:Class="WPFGame.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WPFGame">
〈Canvas x:Name="Carrier" Width="800" Height="600" Background="Silver"
MouseLeftButtonDown="Carrier_MouseLeftButtonDown"/〉
〈/Window〉
For cs file, here is the codes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
namespace WPFGame {
public partial class Window1 : Window {
Rectangle rect;
public Window1() {
InitializeComponent();
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = 50;
rect.Height = 50;
rect.RadiusX = 5;
rect.RadiusY = 5;
Carrier.Children.Add(rect);
Canvas.SetLeft(rect, 0);
Canvas.SetTop(rect, 0);
}
private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
Point p = e.GetPosition(Carrier);
Storyboard storyboard = new Storyboard();
DoubleAnimation doubleAnimation = new DoubleAnimation(
Canvas.GetLeft(rect),
p.X,
new Duration(TimeSpan.FromMilliseconds(500))
);
Storyboard.SetTarget(doubleAnimation, rect);
Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
storyboard.Children.Add(doubleAnimation);
doubleAnimation = new DoubleAnimation(
Canvas.GetTop(rect),
p.Y,
new Duration(TimeSpan.FromMilliseconds(500))
);
Storyboard.SetTarget(doubleAnimation, rect);
Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));
storyboard.Children.Add(doubleAnimation);
//if (!Resources.Contains("rectAnimation")) {
// Resources.Add("rectAnimation", storyboard);
//}
//Play the Animation
storyboard.Begin();
}
}
}
Pust F5, then click the left mouse button on the page, you will see the item move.
