I have two rectangles in my WPF application. I want to play an animation when I click on an element. The animation should be applied to only the clicked rectangle. With the code below, when I click on a rectangle, all the shapes get animated.
What should I do??
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>
and the 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)
{
}
Just set the x:Shared
attribute to false
on your LinearGradientBrush resource. Then each Rectangle's Fill property gets its own copy of the Brush assigned.
<LinearGradientBrush x:Key="ExecutionInitialization" x:Shared="false"
EndPoint="0.5,1" StartPoint="0.5,0">
...
</LinearGradientBrush>
In order to run the animation independently on different Rectangles, you would also have to remove the Storyboard.TargetName
, and start the Storybord with the target control as parameter:
private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
{
var storyboard = TryFindResource("OnMouseLeftButtonDown1") as Storyboard;
storyboard.Begin((FrameworkElement)sender);
}
You might then also use the same event handler for all such Rectangles:
<Rectangle x:Name="rec1" MouseDown="Rectangle_MouseDown" .../>
<Rectangle x:Name="rec2" MouseDown="Rectangle_MouseDown" .../>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With