WPF realizes left right movement (shaking) animation effect
- 2021-10-15 10:22:19
- OfStack
In this paper, we share the specific code of WPF to realize the left and right moving effect display for your reference. The specific contents are as follows
DoubleAnimation and Storyboard are mainly used to realize left-right movement (shaking) of controls or layouts
The layout code is:
<Canvas>
<Grid Width="200" Height="100" Background="MediumAquamarine" Name="GroupboxArea" Canvas.Left="100" Canvas.Top="200"/>
<Button Content="Button" Height="25" Width="78" Click="Button_Click"/>
</Canvas>
The background code is:
private void Button_Click(object sender, RoutedEventArgs e)
{
DoubleAnimation DAnimation = new DoubleAnimation();
DAnimation.From = 100;// Starting point
DAnimation.To = 280;// End point
DAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));// Time
Storyboard.SetTarget(DAnimation, GroupboxArea);
Storyboard.SetTargetProperty(DAnimation, new PropertyPath(Canvas.LeftProperty));
Storyboard story = new Storyboard();
story.Completed += new EventHandler(story_Completed);// What to do after completion
//story.RepeatBehavior = RepeatBehavior.Forever;// Infinite loop, you need to add yourself
story.Children.Add(DAnimation);
story.Begin();
}
void story_Completed(object sender, EventArgs e)
{
DoubleAnimation DAnimation = new DoubleAnimation();
DAnimation.From = 280;// Starting point
DAnimation.To = 100;// End point
DAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));// Time
Storyboard.SetTarget(DAnimation, GroupboxArea);
Storyboard.SetTargetProperty(DAnimation, new PropertyPath(Canvas.LeftProperty));
Storyboard story = new Storyboard();
story.Completed += new EventHandler(storyCompleted);// What to do after completion
//story.RepeatBehavior = RepeatBehavior.Forever;// Infinite loop, you need to add yourself
story.Children.Add(DAnimation);
story.Begin();
}
void storyCompleted(object sender, EventArgs e)
{
DoubleAnimation DAnimation = new DoubleAnimation();
DAnimation.From = 100;// Starting point
DAnimation.To = 200;// End point
DAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));// Time
Storyboard.SetTarget(DAnimation, GroupboxArea);
Storyboard.SetTargetProperty(DAnimation, new PropertyPath(Canvas.LeftProperty));
Storyboard story = new Storyboard();
//story.Completed += new EventHandler(storyCompleted);// What to do after completion
//story.RepeatBehavior = RepeatBehavior.Forever;// Infinite loop, you need to add yourself
story.Children.Add(DAnimation);
story.Begin();
}