WPFAnimatedGif trows 一个 System.OutOfRangeException

WPFAnimatedGif trows an System.OutOfRangeException

我正在尝试通过以下代码从在我的 WPF 应用程序中设置动画的网站获取 gif。 我正在使用 WPFAnimatedGif 库。

Image image = new Image();
var BtmImg = new BitmapImage();
string link = https://media.giphy.com/media/phJ6eMRFYI6CQ/giphy.gif;

BtmImg.BeginInit();
BtmImg.UriSource = new Uri(link);
BtmImg.EndInit();

ImageBehavior.SetAnimatedSource(image, BtmImg);
panel.Children.Add(image); //panel is a stackpanel defined in the xaml

如果我通过代码逐行进入调试模式,或者如果我在 BtmImg.EndInit(); 之前添加一个小睡眠,比如 System.Threading.Thread.Sleep(2000);

,这工作正常

否则我会得到一个异常:System.ArgumentOutOfRangeException:'指定的参数超出了有效值的范围。 参数名称:索引' 此异常最初是在此调用堆栈中抛出的: [外码]

我的猜测是,在我尝试使用 gif 时未完全下载它。

有人知道如何处理吗?

My guess is, that the gif is not fully downloaded as I'm trying to use it.

这正是问题所在。最好的方法是设置在下载完成后调用的回调或事件处理程序,然后继续进行其余设置。在这种情况下,BitmapImage 对象带有一个您可以使用的事件处理程序。

试试这个:

    BtmImg.DownloadCompleted += (s, e) =>
    {
        ImageBehavior.SetAnimatedSource(image, BtmImg);
        panel.Children.Add(image); //panel is a stackpanel de
    };

    BtmImg.BeginInit();
    BtmImg.UriSource = new Uri(link);
    BtmImg.EndInit();