如何将缩放动画添加到加载用户控件

时间:2012-03-12 05:55:34

标签: wpf animation user-controls stackpanel

我想在StackPanel

中为加载用户控件添加动画

所以我将这些行添加到现有项目中:

control.Loaded += UserControlLoaded;

    public void UserControlLoaded(object sender, System.Windows.RoutedEventArgs e)
    {
        UserControl control = (UserControl)sender;

        DoubleAnimation fadeInAnimation = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(5)));
        Storyboard.SetTarget(fadeInAnimation, control);
        Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(UIElement.OpacityProperty));
        Storyboard sb = new Storyboard();
        sb.Children.Add(fadeInAnimation);
        sb.Begin();
    }

它运行良好但是我想改变它以在2秒内将用户控制从0到1扩展到但是我找不到将故事板的目标属性设置为LayoutTransform X和Y轴的代码!

通过这种方式在MS Blend中进行了转换:                                                                                                                                       

我该如何以编程方式完成。

提前感谢您的关注。

1 个答案:

答案 0 :(得分:3)

为控件的LayoutTransform设置动画的代码取决于所使用的Transform类型。如果它只是一个ScaleTransform,你可以这样写:

FrameworkElement control = sender as FrameworkElement;
ScaleTransform transform = control.LayoutTransform as ScaleTransform;
DoubleAnimation scaleAnimation =
    new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(2)));

transform.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
transform.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

当使用Blend创建LayoutTransform时,它肯定不仅仅是ScaleTransform,而是具有ScaleTransform作为第一个子项的TransformGroup。然后,您将通过以下内容检索ScaleTranform:

TransformGroup transformGroup = control.LayoutTransform as TransformGroup;
ScaleTransform transform = transformGroup.Children[0] as ScaleTransform;

我再次忘记了为什么动画像这样的变换无法通过故事板工作的原因。我没有直接在ScaleTransform对象上调用BeginAnimation,而是尝试了下面的代码,但没有成功。

DoubleAnimation xScaleAnimation =
    new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(2)));
Storyboard.SetTarget(xScaleAnimation, transform);
Storyboard.SetTargetProperty(xScaleAnimation,
    new PropertyPath(ScaleTransform.ScaleXProperty));

DoubleAnimation yScaleAnimation =
    new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(2)));
Storyboard.SetTarget(yScaleAnimation, transform);
Storyboard.SetTargetProperty(yScaleAnimation,
    new PropertyPath(ScaleTransform.ScaleYProperty));

Storyboard sb = new Storyboard();
sb.Children.Add(xScaleAnimation);
sb.Children.Add(yScaleAnimation);
sb.Begin();