Saturday, December 10, 2011

Windows Phone 7 - One-liner to animate position and alpha of a UIElement without XAML


  public static Storyboard AnimatePositionAndAlpha(DependencyObject element, double delay, double duration, double startAlpha, double endAlpha, Point startPt, Point endPt)
        {
            Storyboard storyboard = new Storyboard();

            duration *= 20;

            TranslateTransform trans = new TranslateTransform() { X = startPt.X, Y = startPt.Y };

            ((UIElement)element).RenderTransform = trans;
            ((UIElement)element).Opacity = startAlpha;

            DoubleAnimation moveAnimX = new DoubleAnimation();
            moveAnimX.Duration = TimeSpan.FromSeconds(duration);
            moveAnimX.From = startPt.X;
            moveAnimX.To = endPt.X;
            moveAnimX.BeginTime = TimeSpan.FromSeconds(delay);
            Storyboard.SetTarget(moveAnimX, ((UIElement)element));
            Storyboard.SetTargetProperty(moveAnimX, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));

            DoubleAnimation moveAnimY = new DoubleAnimation();
            moveAnimY.Duration = TimeSpan.FromSeconds(duration);
            moveAnimY.BeginTime = TimeSpan.FromSeconds(delay);
            moveAnimY.From = startPt.Y;
            moveAnimY.To = endPt.Y;
            Storyboard.SetTarget(moveAnimY, ((UIElement)element));
            Storyboard.SetTargetProperty(moveAnimY, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.Y)"));



          
            

            
            DoubleAnimation alphaAnim = new DoubleAnimation();
            alphaAnim.From = startAlpha;
            alphaAnim.To = endAlpha;
            alphaAnim.Duration = TimeSpan.FromSeconds(duration);
            alphaAnim.BeginTime = TimeSpan.FromSeconds(delay);
            alphaAnim.AutoReverse = false;
            Storyboard.SetTarget(alphaAnim, element);
            Storyboard.SetTargetProperty(alphaAnim, new PropertyPath(UIElement.OpacityProperty));

            storyboard.Children.Add(moveAnimX);
            storyboard.Children.Add(moveAnimY);
            storyboard.Children.Add(alphaAnim);
         
            
            
            storyboard.Begin();
         
            return storyboard;
        }