.net – How to get an animated gif to work in WPF


What control type should I use – Image, MediaElement, etc.?

Best Solution

I couldn't get the most popular answer to this question (above by Dario) to work properly. The result was weird, choppy animation with weird artifacts. Best solution I have found so far: https://github.com/XamlAnimatedGif/WpfAnimatedGif

You can install it with NuGet

PM> Install-Package WpfAnimatedGif

and to use it, at a new namespace to the Window where you want to add the gif image and use it as below

<Window x:Class="MainWindow"
    xmlns:gif="http://wpfanimatedgif.codeplex.com" <!-- THIS NAMESPACE -->
    Title="MainWindow" Height="350" Width="525">

    <Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" />

The package is really neat, you can set some attributes like below

<Image gif:ImageBehavior.RepeatBehavior="3x"
       gif:ImageBehavior.AnimatedSource="Images/animated.gif" />

and you can use it in your code as well:

var image = new BitmapImage();
image.UriSource = new Uri(fileName);
ImageBehavior.SetAnimatedSource(img, image);

EDIT: Silverlight support

As per josh2112's comment if you want to add animated GIF support to your Silverlight project then use github.com/XamlAnimatedGif/XamlAnimatedGif