我在将一些动画方法从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;
}
}
现在,我有一个静态类,其中包含我用来管理动画的方法。
我需要使用不透明度和缩放动画创建一个Storyboard然后返回它,这样我就可以为其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的引用,所以它没有工作(至少,我没有做过)设法让它以这种方式工作。)
此代码有什么问题?
谢谢!
塞尔吉奥
答案 0 :(得分:1)
尝试使用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"));