如何在没有代码绑定的情况下获得在WPF字典中工作的动画gif

本文关键字:字典 WPF 工作 gif 动画 情况下 代码 绑定 | 更新日期: 2023-09-27 18:21:24

我有一个字典,它使用了另一个类的数据模板,字典后面没有代码,只有XAML

我需要一个动画gif作为这本字典的一部分。

尝试这样做:

var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("myprojectname.Resources.theGifToUse.gif");
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
picturebox = image;

和在XAML中:

<WindowsFormsHost>
   <forms:PictureBox x:Name="pictu1rebox" Image="{Binding picturebox}"/>
</WindowsFormsHost>

但它不起作用!

不使用WpfAnimatedGif.dll最简单的方法是什么?

感谢

如何在没有代码绑定的情况下获得在WPF字典中工作的动画gif

标准BitmapImage不支持播放.gif文件。我知道的唯一选项是使用Bitmap。它具有ImageAnimator。完整示例:

XAML

<Window x:Class="PlayGifHelp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="MainWindow_Loaded">
    <Grid>
        <Image x:Name="SampleImage" />
    </Grid>
</Window>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    Bitmap _bitmap;
    BitmapSource _source;
    private BitmapSource GetSource()
    {
        if (_bitmap == null)
        {
            string path = Directory.GetCurrentDirectory();
            // Check the path to the .gif file
            _bitmap = new Bitmap(path + @"'anim.gif");
        }
        IntPtr handle = IntPtr.Zero;
        handle = _bitmap.GetHbitmap();
        return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
    }
    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        _source = GetSource();
        SampleImage.Source = _source;
        ImageAnimator.Animate(_bitmap, OnFrameChanged);
    }
    private void FrameUpdatedCallback()
    {
        ImageAnimator.UpdateFrames();
        if (_source != null)
        {
            _source.Freeze();
        }
        _source = GetSource();
        SampleImage.Source = _source;
        InvalidateVisual();
    }
    private void OnFrameChanged(object sender, EventArgs e)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(FrameUpdatedCallback));
    }
}

Bitmap不支持URI指令,所以我从当前目录加载.gif文件。