![](/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.