Spinning Image When Mouse Pointer on Button in WPF

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.

  1. <Grid Margin="0,246,228,0">  
  2.     <Button Name="imagebtn"  
  3.   
  4. Grid.Column="0"  
  5.   
  6. Margin="121,-229,-111,25"  
  7.   
  8. Command="{Binding RefreshPortList}" HorizontalAlignment="Left" Width="279" >  
  9.         <Image Source="Koala.jpg"  
  10.   
  11. RenderTransformOrigin=".5,.5"  
  12.   
  13. Height="268" Width="269">  
  14.             <Image.RenderTransform>  
  15.                 <RotateTransform x:Name="RotateTransform" Angle="0" />  
  16.             </Image.RenderTransform>  
  17.             <Image.Triggers>  
  18.                 <EventTrigger RoutedEvent="MouseLeave">  
  19.                     <BeginStoryboard>  
  20.                         <Storyboard>  
  21.                             <DoubleAnimation Storyboard.TargetName="RotateTransform"  
  22.   
  23. Storyboard.TargetProperty="Angle"  
  24.   
  25. By="10"  
  26.   
  27. To="360"  
  28.   
  29. Duration="0:0:0.7"  
  30.   
  31. FillBehavior="Stop"/>  
  32.                         </Storyboard>  
  33.                     </BeginStoryboard>  
  34.                 </EventTrigger>  
  35.             </Image.Triggers>  
  36.         </Image>  
  37.     </Button>  
  38. </Grid>  
  • For MouseEnter we need to change just a single line of code in the preceding XAML as in the following:
  1. <EventTrigger RoutedEvent="MouseEnter">  
  • Similarly For MouseLeave:
  1. <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.

Up Next
    Ebook Download
    View all
    Learn
    View all