建立名為 Carrier 的 Canvas(800×600,銀色背景),註冊滑鼠左鍵點擊事件。選擇 Canvas 因其支援子元素絕對定位,便於處理物體移動。
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);
}
建立 50×50 圓角紅色方塊,加入 Carrier,初始位置 (0,0)。
private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
Point p = e.GetPosition(Carrier);
Storyboard storyboard = new Storyboard();
// X 軸動畫
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);
// Y 軸動畫
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);
storyboard.Begin();
}
點擊處即為目標座標,分別建立 X、Y 方向的 DoubleAnimation,目標屬性為 Canvas.Left/Top,時長 500ms,加入 Storyboard 播放。