新手WPF动画:如何开始动画?

时间:2014-01-09 14:02:50

标签: c# wpf animation

我创建了一个自定义动画类,遵循此准则WPF Tutorial - Part 2

public class EarthAnimation : AnimationTimeline
{
    private Earth _earth = new Earth(250);

    public static readonly DependencyProperty FromProperty =
    DependencyProperty.Register("From", typeof (int), typeof (EarthAnimation),
    new PropertyMetadata(default(int)));

    public int From
    {
        get { return (int) GetValue(FromProperty); }
        set { SetValue(FromProperty, value); }
    }

    public static readonly DependencyProperty ToProperty =
    DependencyProperty.Register("To", typeof (int), typeof (EarthAnimation), new PropertyMetadata(default(int)));

    public int To
    {
        get { return (int) GetValue(ToProperty); }
        set { SetValue(ToProperty, value); }
    }

    protected override Freezable CreateInstanceCore()
    {
        return new EarthAnimation();
    }

    public override Type TargetPropertyType
    {
        get { return typeof (int); }
    }

    public override object GetCurrentValue(object defaultOriginValue, object defaultDestinationValue,
    AnimationClock animationClock)
    {
        Vector fromVal = ((Earth) GetValue(EarthAnimation.FromProperty)).Coords;
        Vector toVal = ((Earth) GetValue(EarthAnimation.ToProperty)).Coords;


        return new DenseVector(new[]
        {
            _earth.DistanceToStar*Math.Cos(_earth.WE*animationClock.CurrentProgress.Value),
            _earth.BE*Math.Sin(_earth.WE*animationClock.CurrentProgress.Value)
        });
    }
}

我的Xaml看这个(简化):

<Grid Name="MyCanvasGrid"
    Width="600"
    Height="400"
    Background="Transparent"
    RenderTransformOrigin="0.5,0.5">

    <Canvas x:Name="CanvasDrawingArea"
        Grid.Row="0"
        Width="Auto"
        Height="Auto"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        ClipToBounds="False"
        RenderTransformOrigin="0.5,0.5"
        RenderTransform="1 0 0 -1 0 0">
    </Canvas>
</Grid>

我想在按下PlayBt时开始动画( in Code )。

private void PlayBt_OnClick(object sender, RoutedEventArgs e)
{
    DrawEarth();    
    var dbAnim = new EarthAnimation();

    dbAnim.Duration = new Duration(TimeSpan.FromSeconds(4));
    dbAnim.RepeatBehavior = RepeatBehavior.Forever;

    // Set the start value and end value. 
    dbAnim.From = 1;
    dbAnim.To = 3660;
}

如何在代码中开始动画?

1 个答案:

答案 0 :(得分:-2)

对于“开始动画”,您需要使用“Begin()”;

功能启动动画
dbAnim.Begin();