![](/img/trans.png)
[英]How to animate TranslateTransform and ScaleTransform in WPF
[英]Animate ScaleTransform of a Grid inside a UserControl programmatically in WPF
将WinRT的某些动画方法移植到WPF时遇到问题。
我在UserControl中有一个Grid,我基本上想在不降低不透明度的情况下扩大网格,然后再将其不透明度恢复到正常水平进行缩放。
这是UserControl XAML的一部分:
<Grid x:Name="myGrid">
<Grid.RenderTransform>
<ScaleTransform x:Name="scaleTransform"/>
</Grid.RenderTransform>
<!--Stuff here-->
</Grid>
然后在UserControl的.cs文件中使用以下两个属性在代码中获取这些对象:
public Grid MyGrid
{
get
{
return myGrid;
}
}
public ScaleTransform GridScaleTransform
{
get
{
return scaleTransform;
}
}
现在,我有了一个静态类,其中包含用于管理动画的方法。
我需要创建一个具有不透明度和缩放动画的情节提要,然后将其返回,以便可以向其Closed事件添加一些处理程序,然后启动它。
这是无法正常工作的静态方法:
private static Storyboard createGridAnimation(MyUserControl element, double fromScale, double toScale, bool animIn = false)
{
Storyboard storyboard = new Storyboard();
//Add the opacity animation only if the animation is the one that scales up the grid
if (animIn)
{
DoubleAnimationUsingKeyFrames opacityAnim= new DoubleAnimationUsingKeyFrames();
opacityAnim.Duration = new Duration(TimeSpan.FromMilliseconds(200));
//Some keyframes here...
Storyboard.SetTarget(opacityAnim, element.MyGrid);
Storyboard.SetTargetProperty(opacityAnim, new PropertyPath(UIElement.OpacityProperty));
storyboard.Children.Add(opacityAnim);
}
//Scale X
DoubleAnimation scaleXAnimation = new DoubleAnimation() { From = fromScale, To = 2.0, AutoReverse = false };
scaleXAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(100));
Storyboard.SetTarget(scaleXAnimation, element.GridScaleTransform);
Storyboard.SetTargetProperty(scaleXAnimation, new PropertyPath(ScaleTransform.ScaleXProperty));
//Scale Y
DoubleAnimation scaleYAnimation = new DoubleAnimation() { From = fromScale, To = 2.0, AutoReverse = false };
scaleXAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(100));
Storyboard.SetTarget(scaleYAnimation, elemento.GridScaleTransform);
Storyboard.SetTargetProperty(scaleYAnimation, new PropertyPath(ScaleTransform.ScaleYProperty));
storyboard.Children.Add(scaleXAnimation);
storyboard.Children.Add(scaleYAnimation);
return storyboard;
}
问题在于,唯一起作用的动画是不透明度动画,两个scaleTransform doubleAnimations根本就不会启动。 我读到可以尝试使用SetTargetName属性,但是由于我位于静态方法中,并且仅具有对目标UIElement的引用,因此它不起作用(至少,我没有设法使其起作用)方式)。
此代码有什么问题?
谢谢!
塞尔吉奥
尝试使用Grid作为目标元素:
Storyboard.SetTarget(scaleXAnimation, element.MyGrid);
Storyboard.SetTargetProperty(scaleXAnimation,
new PropertyPath("RenderTransform.ScaleX"));
Storyboard.SetTarget(scaleYAnimation, element.MyGrid);
Storyboard.SetTargetProperty(scaleYAnimation,
new PropertyPath("RenderTransform.ScaleY"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.