Spinning an image on MouseEnter/MouseLeave on Button in a WPF Application
Spinning an image in WPF is a very simple and useful task for making our application more attractive. It only uses Trigger and StoryBoard.
- Triggers are used to do certain actions when a specified condition is fulfilled.
- Storyboard objects enable you to combine timelines that affect a variety of objects and properties into a single timeline tree and make it easy to organize and control complex timing behaviors.
Here is the XAML code for spinning an image on MouseEnter or MouseLeave that is applied on a button.
- <Grid Margin="0,246,228,0">
- <Button Name="imagebtn"
-
- Grid.Column="0"
-
- Margin="121,-229,-111,25"
-
- Command="{Binding RefreshPortList}" HorizontalAlignment="Left" Width="279" >
- <Image Source="Koala.jpg"
-
- RenderTransformOrigin=".5,.5"
-
- Height="268" Width="269">
- <Image.RenderTransform>
- <RotateTransform x:Name="RotateTransform" Angle="0" />
- </Image.RenderTransform>
- <Image.Triggers>
- <EventTrigger RoutedEvent="MouseLeave">
- <BeginStoryboard>
- <Storyboard>
- <DoubleAnimation Storyboard.TargetName="RotateTransform"
-
- Storyboard.TargetProperty="Angle"
-
- By="10"
-
- To="360"
-
- Duration="0:0:0.7"
-
- FillBehavior="Stop"/>
- </Storyboard>
- </BeginStoryboard>
- </EventTrigger>
- </Image.Triggers>
- </Image>
- </Button>
- </Grid>
- For MouseEnter we need to change just a single line of code in the preceding XAML as in the following:
- <EventTrigger RoutedEvent="MouseEnter">
- Similarly For MouseLeave:
- <EventTrigger RoutedEvent="MouseLeave">
That's It.
If anyone is a beginner in WPF then please try this. You will find this very Interesting and very useful.