在BeginAnimation中指定UIElement的DependencyProperty

时间:2015-08-26 09:19:09

标签: wpf animation render dependency-properties

我正在尝试动画椭圆以从画布上的A点移动到B点。

public void AnimateSensor(double x, double y, Ellipse sensor)
    {
        if (!Double.IsNaN(x))
        {
            DoubleAnimation animX = new DoubleAnimation();
            animX.To = x;
            animX.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
            DoubleAnimation animY = new DoubleAnimation();
            animY.To = y;
            animY.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
            TranslateTransform rt = new TranslateTransform();
            sensor.RenderTransform = rt;

            rt.BeginAnimation(sensor.GetValue(Canvas.TopProperty), animX);
            rt.BeginAnimation(sensor.GetValue(Canvas.LeftProperty), animY);
           }
        else
            Console.WriteLine("x or y is NaN");
    }

我用一组坐标和一个Ellipse调用这个方法,但我似乎无法弄清楚如何在BeginAnimation中指定依赖值。我尝试了'sensor.GetValue(Canvas.LeftProperty)',但它说它是一个对象,需要一个依赖属性。当我使用'as DependencyProperty'时它使它为null,当我尝试转换它时,它说你不能从double转换为DependencyProperty。

1 个答案:

答案 0 :(得分:2)

您可以为Ellipse的Canvas.LeftCanvas.Top属性设置动画,而无需TranslateTransform,如下所示:

sensor.BeginAnimation(Canvas.LeftProperty, animX);
sensor.BeginAnimation(Canvas.TopProperty, animY);

或TranslateTransform的XY属性,如下所示:

if (!(sensor.RenderTransform is TranslateTransform))
{
    // assign RenderTransform only once
    sensor.RenderTransform = new TranslateTransform();
}

var transform = (TranslateTransform)sensor.RenderTransform;
transform.BeginAnimation(TranslateTransform.XProperty, animX);
transform.BeginAnimation(TranslateTransform.YProperty, animY);