One of the things that came along with WPF was the ability to create animations declaratively in XAML. I wanted to create a working-in-the-background spinner for a WPF application I was working on, and I thought that it would be a breeze with such powerful capability. However, I had a surprisingly difficult time finding a nice, simple example on the internet!
After a lot of looking and a bit of tinkering, I was able to come up with a solution that I’m mostly satisfied with. It’s a little more verbose than I was hoping for, but it’s still a XAML-only solution, which is what I was ultimately seeking.
Some notes about the solution:
- The CenterX and CenterY properties of the RotateTransform element must be half of the image to make it rotate around the center of the image. My image is 24×24, so the X and Y centers are 12 and 12, respectively.
- The DoubleAnimation will run on an infinite loop from angle 0 to 360 over a 1 second duration.
- The storyboard will be active while the image’s IsEnabled property is set to True.
<Image Source="gear_24x24.png" Height="24"> <Image.RenderTransform> <RotateTransform CenterX="12" CenterY="12" /> </Image.RenderTransform> <Image.Style> <Style> <Style.Triggers> <Trigger Property="Image.IsEnabled" Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Angle" From="0" To="360" Duration="0:0:1" RepeatBehavior="Forever" /> </Storyboard> </BeginStoryboard> </Trigger.EnterActions> </Trigger> </Style.Triggers> </Style> </Image.Style> </Image>
You could also extract the animation code away into a resource. This will improve reusability and keep your XAML cleaner if you have multiple spinners, but it’s more of a preference when dealing with a single spinner.
<Window.Resources> <Style x:Key="Spinner" TargetType="Image"> <Setter Property="Height" Value="24" /> <Setter Property="Image.RenderTransform"> <Setter.Value> <RotateTransform CenterX="12" CenterY="12" /> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="IsEnabled" Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="RenderTransform.Angle" From="0" To="360" Duration="0:0:1" RepeatBehavior="Forever" /> </Storyboard> </BeginStoryboard> </Trigger.EnterActions> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Image Source="gear_24x24.png" Style="{StaticResource Spinner}" /> </Grid>
This solution is based on this post.
Thanks so much for your tutorial,. it has helped me achieve a lot on creating my DJ mix application. http://goo.gl/6M50tZ