why does it not work the way it should? There is no movement…. below is the code:
namespace MovingBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Storyboard myStoryboard = new Storyboard();
public MainWindow()
{
InitializeComponent();
}
private void Start_Animation(object sender, EventArgs e)
{
myStoryboard.Begin();
}
private void MyAnimatedRectangle_MouseDown(object sender, MouseButtonEventArgs e)
{
Start_Animation(sender, e);
}
}
}
XAML:
<Window x:Class="MovingBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<StackPanel.Resources>
<Storyboard x:Name="myStoryboard" x:Key="myStoryboardKey">
<DoubleAnimation
Storyboard.TargetName="MyAnimatedRectangle"
Storyboard.TargetProperty="Opacity"
From="1.0" To="0.0" Duration="0:0:5"
AutoReverse="True" RepeatBehavior="Forever" />
</Storyboard>
</StackPanel.Resources>
<Rectangle Loaded="Start_Animation" x:Name="MyAnimatedRectangle"
Width="100" Height="100" Fill="Blue" MouseDown="MyAnimatedRectangle_MouseDown" />
</StackPanel>
</Grid>
The myStoryBoard you are referring to in the Start_Animation method is a different one from the one in the XAML.
Here’s a working version that searches for the storyboard resource:
Note that I removed the
Storyboard myStoryboard = new Storyboard();