I am using this code for gif Animating in seprate library and xaml code in my main project:
There is a much easier way to show an animated .gif in wpf - use the MediaElement
Example:
<MediaElement x:Name="myGif" MediaEnded="myGif_MediaEnded" UnloadedBehavior="Manual" Source="file://C:\waiting.GIF" LoadedBehavior="Play" Stretch="None"/>
If you want the .gif to loop endlessly but it only specifies a limited amount of repeats in the .gif file, you can hook MediaEnded
and just restart the animation (Be sure to set the UnloadedBehavior
to Manual
):
private void myGif_MediaEnded(object sender, RoutedEventArgs e)
{
myGif.Position = new TimeSpan(0, 0, 1);
myGif.Play();
}
Try this:
<controls:GifImage GifSource="/Images/my.gif" Stretch="None" />
BTW, I found using this way to play gif in wpf might deform some gif images, and I wonder why...
I can't take credit for this but here's a way to do this in XAML only. I added an "IsBusy" property to my ViewModel to show/hide the spinner during processing.
<Image Name="Spinner" Source="Resources/spinner.gif" RenderTransformOrigin="0.5, 0.5">
<Image.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard Storyboard.TargetName="Spinner" Storyboard.TargetProperty="RenderTransform.(RotateTransform.Angle)">
<DoubleAnimation From="0" To="360" BeginTime="0:0:0" Duration="0:0:2" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Image.Triggers>
<Image.RenderTransform>
<RotateTransform Angle="0" />
</Image.RenderTransform>
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding IsBusy}" Value="False">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
Here's the link to the author's solution.