2010-05-28 76 views
6

作为展览,我试图在ScaleTransform的ScaleX和ScaleY属性上使用DoubleAnimation。我有一个长方形(144x144),我想在五秒内做出长方形。ScaleTransform中的DoubleAnimation

我的XAML:

<Window x:Class="ScaleTransformTest.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded"> 
    <Grid> 
     <Rectangle Name="rect1" Width="144" Height="144" Fill="Aqua"> 
      <Rectangle.RenderTransform> 
       <ScaleTransform ScaleX="1" ScaleY="1" /> 
      </Rectangle.RenderTransform> 
     </Rectangle> 
    </Grid> 
</Window> 

我的C#:

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    ScaleTransform scaly = new ScaleTransform(1, 1); 
    rect1.RenderTransform = scaly; 

    Duration mytime = new Duration(TimeSpan.FromSeconds(5)); 
    Storyboard sb = new Storyboard(); 

    DoubleAnimation danim1 = new DoubleAnimation(1, 1.5, mytime); 
    DoubleAnimation danim2 = new DoubleAnimation(1, 0.5, mytime); 
    sb.Children.Add(danim1); 
    sb.Children.Add(danim2); 

    Storyboard.SetTarget(danim1, scaly); 
    Storyboard.SetTargetProperty(danim1, new PropertyPath(ScaleTransform.ScaleXProperty)); 
    Storyboard.SetTarget(danim2, scaly); 
    Storyboard.SetTargetProperty(danim2, new PropertyPath(ScaleTransform.ScaleYProperty)); 

    sb.Begin(); 
} 

不幸的是,当我运行这个程序,它什么都不做。矩形保持在144x144。如果我不使用动画,只是

ScaleTransform scaly = new ScaleTransform(1.5, 0.5); 
rect1.RenderTransform = scaly; 

它会立即拉长它,没问题。其他地方有一个问题。有什么建议么?我已阅读http://www.eggheadcafe.com/software/aspnet/29220878/how-to-animate-tofrom-an.aspx的讨论,其中有人似乎已经获得了pure-XAML版本,但代码未显示在那里。

编辑:在Applying animated ScaleTransform in code problem似乎有人有一个非常类似的问题,我很好用他的方法工作,但到底是什么string thePath = "(0).(1)[0].(2)";?这些数字代表什么?

回答

7

事情是这样的,这是从MSDN的Storyboards Overview项报价,在标题为“这里可以用一个Storyboard?”:

A Storyboard can be used to animate dependency properties of animatable classes (for more information about what makes a class animatable, see the Animation Overview). However, because storyboarding is a framework-level feature, the object must belong to the NameScope of a FrameworkElement or a FrameworkContentElement.

这让我思考的是,ScaleTransform对象不属于任何FrameworkElementNameScope。即使RectangleFrameworkElement,因为ScaleTransform不是其逻辑孩子的一部分,而是分配给其他某个属性的值(在此例中为RenderTransform属性)。

要解决这个问题,你需要修改你的目标对象和PropertyPath,即:

Storyboard.SetTarget(danim1, rect1); 
Storyboard.SetTargetProperty(danim1, 
    new PropertyPath("RenderTransform.(ScaleTransform.ScaleX)")); 

尝试过了,它的作品,即使我并不完全来自MSDN自己了解报价:-)

+0

其实,我得到这个错误: 无法解析属性路径'RenderTransform。(ScaleTransform.ScaleX)'中的所有属性引用。验证适用的对象是否支持这些属性。 您确定您正确复制/粘贴您的工作代码? – 2010-05-28 20:19:55

+0

不确定,我发现了17分钟前更正的复制/粘贴错误。 – 2010-05-28 20:31:01

+0

仍然不适合你?我向你保证,它适用于.NET 4和VS2010。 – 2010-05-31 19:02:02