2010-05-28 78 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