2014-07-21 76 views
5

我的WPF應用程序中有兩個矩形。我想單擊某個元素時播放動畫。動畫只應用於點擊矩形。用下面的代碼,當我點擊一個矩形時,所有的形狀都會變成動畫。故事板適用於很多元素

我該怎麼辦?

Window.Resources> 
    <ResourceDictionary> 

      <LinearGradientBrush x:Key="ExecutionInitialization" EndPoint="0.5,1" StartPoint="0.5,0"> 
       <GradientStop Color="#FFC0FBBA"/> 
       <GradientStop Color="#FF0FA000" Offset="1"/> 
       <GradientStop Color="#FF0FA000"/> 
      </LinearGradientBrush> 

     <Storyboard x:Key="OnMouseLeftButtonDown1" RepeatBehavior="Forever"> 
      <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Offset)" Storyboard.TargetName="rec1"> 
       <SplineDoubleKeyFrame KeyTime="0" Value="0.17"/> 
       <SplineDoubleKeyFrame KeyTime="0:0:0.4" Value="0.32"/> 
       <SplineDoubleKeyFrame KeyTime="0:0:0.8" Value="0.5"/> 
       <SplineDoubleKeyFrame KeyTime="0:0:1" Value="0.56"/> 
       <SplineDoubleKeyFrame KeyTime="0:0:1.2" Value="1"/> 
      </DoubleAnimationUsingKeyFrames> 
     </Storyboard> 
    </ResourceDictionary> 


</Window.Resources> 

<Grid> 
    <Rectangle MouseDown="rec1_MouseDown" Name="rec1" Fill="{StaticResource ExecutionInitialization}" HorizontalAlignment="Left" Height="85.075" Margin="24.358,27.731,0,0" Stroke="Red" VerticalAlignment="Top" Width="156.717"/> 

    <Rectangle MouseDown="rec2_MouseDown" Name="rec2" Fill="{StaticResource ExecutionInitialization}" HorizontalAlignment="Left" Height="113.433" Margin="246.746,141.164,0,0" Stroke="Black" VerticalAlignment="Center" Width="211.941"/> 

</Grid> 

和C#

public MainWindow() 
{ 
    InitializeComponent(); 
    animation = TryFindResource("OnMouseLeftButtonDown1") as Storyboard; 
} 

private void rec1_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    animation.Begin(); 
} 

private void rec2_MouseDown(object sender, MouseButtonEventArgs e) 
{ 

} 

回答

3

只需設置x:Shared屬性false您一個LinearGradientBrush資源。然後每個Rectangle的Fill屬性都會獲得它自己的Brush分配副本。

<LinearGradientBrush x:Key="ExecutionInitialization" x:Shared="false" 
        EndPoint="0.5,1" StartPoint="0.5,0"> 
    ... 
</LinearGradientBrush> 

爲了在不同的矩形獨立運行的動畫,你也必須與目標控制,參數中刪除Storyboard.TargetName,並啓動Storybord:

private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    var storyboard = TryFindResource("OnMouseLeftButtonDown1") as Storyboard; 
    storyboard.Begin((FrameworkElement)sender); 
} 

你可能那麼也可以使用所有這些矩形的相同事件處理程序:

<Rectangle x:Name="rec1" MouseDown="Rectangle_MouseDown" .../> 
<Rectangle x:Name="rec2" MouseDown="Rectangle_MouseDown" .../>