1 <Canvas
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
4 <Rectangle
5 x:Name="MyAnimatedRectangle"
6 Width="100"
7 Height="100"
8 Fill="Blue">
9 <Rectangle.Triggers>
10
11 <!-- Animates the rectangle‘s opacity. -->
12 <EventTrigger RoutedEvent="Rectangle.Loaded">
13 <BeginStoryboard>
14 <Storyboard>
15 <DoubleAnimation
16 Storyboard.TargetName="MyAnimatedRectangle"
17 Storyboard.TargetProperty="Opacity"
18 From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" />
19 </Storyboard>
20 </BeginStoryboard>
21 </EventTrigger>
22 </Rectangle.Triggers>
23 </Rectangle>
24 </Canvas>
在Canvas下有一个长100px宽100px的的Rectangle对象,在Rectangle的Targegers节点下,定义了一个动画规则,该动画是用来修改Rectangle的透明度(Opacity)属性的,
有了这样的一个例子,我们知道我们要实现Line动态显示效果,就必不可少要用到的对象有Storyboard对象,且要在该对象下制定一个修改X2,Y2的方式(是按照DoubleAnnimation还是ColorAnimation,还是其他方式)
private void myButton_Click(object sender, RoutedEventArgs e)
{
Line myLine = new Line();
myLine.X1 = 500;
myLine.Y1 = 500;
myLine.X2 = 500;
myLine.Y2 = 500;
myLine.Stroke = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
myLine.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
// 把矩形加入到Canvas中
this.cnsDesignerContainer.Children.Add(myLine);
// 创建二个double型的动画,并设定播放时间为2秒
Duration duration = new Duration(TimeSpan.FromSeconds(2));
DoubleAnimation myDoubleAnimation1 = new DoubleAnimation();
DoubleAnimation myDoubleAnimation2 = new DoubleAnimation();
myDoubleAnimation1.Duration = duration;
myDoubleAnimation2.Duration = duration;
// 创建故事版,并加入上面的二个double型动画
Storyboard sb = new Storyboard();
sb.Duration = duration;
sb.Children.Add(myDoubleAnimation1);
sb.Children.Add(myDoubleAnimation2);
// 设置动画的Target目标值
Storyboard.SetTarget(myDoubleAnimation1, myLine);
Storyboard.SetTarget(myDoubleAnimation2, myLine);
// 设置动画的变化属性
Storyboard.SetTargetProperty(myDoubleAnimation1, new PropertyPath("(X2)"));
Storyboard.SetTargetProperty(myDoubleAnimation2, new PropertyPath("(Y2)"));
myDoubleAnimation1.To = 200;
myDoubleAnimation2.To = 200;
if (!cnsDesignerContainer.Resources.Contains("unique_id"))
{
// 将动画版加入Canvas资源,注意:这里的unique_id必须是资源中没有的唯一键
cnsDesignerContainer.Resources.Add("unique_id", sb);
sb.Completed += new EventHandler(sb_Completed);
// 播放
sb.Begin();
}
else
{
sb = null;
cnsDesignerContainer.Children.Remove(myLine);
}
}
void sb_Completed(object sender, EventArgs e)
{
// 播放完成后,移除资源,否则再次点击时将报错
cnsDesignerContainer.Resources.Remove("unique_id");
}