WPF绑定图片引起的文件被占用异常的解决方案

来源:互联网 发布:单片机驱动程序 编辑:程序博客网 时间:2024/05/17 22:18

    WPF默认的Image控件绑定Source后,图片文件会被占用,此时删除或者使用另一Image控件绑定该图片,将引起文件被占用异常。甚至当Image控件删除后仍会存在文件被占用的异常,资料给出的解释是Image控件没有Dispose方法导致文件未被释放,这一问题给图片绑定的便捷操作带来了很多麻烦。

    解决思路:绑定图片时,我们从文件读取为字节并释放文件。创建bitmap图像,使用读取的字节初始化bitmap已达到进一步初始化Image控件的目的,从根本上解决文件占用的问题。上干货,以供参考:

  

/// <summary>    /// ID:为解决WPF BitmapImage图片资源无法删除,文件正在被另一个进程使用问题的方案     /// Describe:自定义图片,加载后释放图片资源    /// Author:ybx    /// Date:2016-12-7 17:51:33    /// </summary>    public class BxImage : Image    {        public new string Source        {            get { return (string)GetValue(SourceProperty); }            set { SetValue(SourceProperty, value); }        }        // Using a DependencyProperty as the backing store for BxSource.  This enables animation, styling, binding, etc...        public new static readonly DependencyProperty SourceProperty =            DependencyProperty.Register("Source", typeof(string), typeof(BxImage), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(BxImage.OnSourceChanged), null), null);        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)        {            Image image = (Image)d;            if (e.NewValue == null || string.IsNullOrEmpty(e.NewValue.ToString()) || !File.Exists(e.NewValue.ToString()))                return;            using (BinaryReader reader = new BinaryReader(File.Open(e.NewValue.ToString(), FileMode.Open)))            {                try                {                    FileInfo fi = new FileInfo(e.NewValue.ToString());                    byte[] bytes = reader.ReadBytes((int)fi.Length);                    reader.Close();                    BitmapImage bitmapImage = new BitmapImage();                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;                    bitmapImage.BeginInit();                    bitmapImage.StreamSource = new MemoryStream(bytes);                    bitmapImage.EndInit();                    image.Source = bitmapImage;                }                catch (Exception) { }            }        }    }

原创粉丝点击