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

    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) { }
            }
        }
    }

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值