<Grid x:Name="LayoutRoot" Background="white" Width="450" Height="450">
<Canvas Background="Red" x:Name="canvasForBackground" MouseLeftButtonDown="getMousePosition">
<Canvas.Resources>
<Storyboard x:Name="moveEllipse">
<DoubleAnimation x:Name="moveEllipse_moveX"
Storyboard.TargetName="MyAnimatedRectangle"
Storyboard.TargetProperty="(Ellipse.RenderTransform).X"
From="10" To="100" Duration="0:0:1"/>
<DoubleAnimation x:Name="moveEllipse_moveY"
Storyboard.TargetName="MyAnimatedRectangle"
Storyboard.TargetProperty="(Ellipse.RenderTransform).Y"
From="10" To="100" Duration="0:0:1"/>
</Storyboard>
</Canvas.Resources>
<Ellipse x:Name="MyAnimatedRectangle" Stroke="Black"
StrokeThickness="4" Fill="Red" Width="50" Height="50" >
<Ellipse.RenderTransform>
<TranslateTransform X="200" Y="200"/>
</Ellipse.RenderTransform>
</Ellipse>
</Canvas>
</Grid>
上述內容中,有先設定好的Silverlight元件動畫:
<Canvas.Resources>
<Storyboard x:Name="moveEllipse">
<DoubleAnimation x:Name="moveEllipse_moveX" Storyboard.TargetName="MyAnimatedRectangle" Storyboard.TargetProperty="(Ellipse.RenderTransform).X"
From="10" To="100" Duration="0:0:1"/>
<DoubleAnimation x:Name="moveEllipse_moveY" Storyboard.TargetName="MyAnimatedRectangle" Storyboard.TargetProperty="(Ellipse.RenderTransform).Y"
From="10" To="100" Duration="0:0:1"/>
</Storyboard>
</Canvas.Resources>
在同一個Storyboard中,可以加入兩個DoubleAnimation(如上述Storyboard包函了「moveEllipse_moveX」、「moveEllipse_moveY」兩個DoubleAnimation),當名為「canvasForBackground」的Canvas元件被按下後,會進入getMousePosition函式,觸發此Storyboard動畫,相對應的C#程式內容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
namespace MoveWithMouse
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void getMousePosition(object sender, MouseButtonEventArgs e)
{
TranslateTransform tt =
MyAnimatedRectangle.RenderTransform as TranslateTransform;
Point pos;
pos = e.GetPosition(canvasForBackground);
moveEllipse_moveX.From = tt.X;
moveEllipse_moveX.To = pos.X - 25;
moveEllipse_moveY.From = tt.Y;
moveEllipse_moveY.To = pos.Y - 25;
moveEllipse.Begin();
}
}
}
其中「moveEllipse_moveX」即是.xaml檔中,Storyboard之下其中一個DoubleAnimation的名字,在程式中將其「From」的屬性改為當下Silverlight元件的位置。
其中有一行如「 moveEllipse_moveX.To = pos.X - 25;」,其需要減去25的原因在於此Ellipse元件的Width值為50,減去25之後,元件移動後,元件中心才會正確到達指定點。
沒有留言:
張貼留言