如何在WPF(C#)中清除图像控件 [英] How to Clear an image control in WPF (C#)

查看:584
本文介绍了如何在WPF(C#)中清除图像控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的C驱动器中有一个带有源图像的图像控件.每当我尝试删除原始图像以将其动态更改为另一图像时,都会收到一条消息,指出该图像正被另一进程使用.如何从图像控件释放图像以将其删除.

我尝试了以下变体:

I have an image control with a source image located in my c drive. I get a message that the image is being used by another process whenever I try to delete the original image to change it with another one dynamically. How do I release the image from the image control to be able to delete it.

I tried this variants:

string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.SetValue(System.Windows.Controls.Image.SourceProperty, null);
File.Delete(path);


并且:


And:

string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.Source = null;
File.Delete(path)



但这不行...

调用DeleteImage方法时,此代码会产生以下错误:

该进程无法访问文件"C:\ Picther.jpg",因为该文件正在被另一个进程使用.



But it''s not work...

This code produces the following error when the DeleteImage method is called:

The process cannot access the file ''C:\Picther.jpg'' because it is being used by another process.

推荐答案

您好,

实现这一点有些棘手,因为ImageControl无法处理BitmapImage中的BitmapStream.
BitmapCacheOption.OnLoad属性解决了此问题,如下所示:

Hi,

it''s a bit tricky to achieve this because BitmapStream from BitmapImage couldn''t be disposed by ImageControl.
BitmapCacheOption.OnLoad Property solves this problem, like this:

public MainWindow()
      {
          InitializeComponent();
           //Display your image in Image Control
          image1.Source = BitmapFromUri(new Uri(@"c:\test.jpg"));
      }

      private void button_DEL_Image_Click(object sender, RoutedEventArgs e)
      {
          image1.Source = null;
          File.Delete(@"c:\test.jpg");
      }

      public static ImageSource BitmapFromUri(Uri source)
      {
          var bitmap = new BitmapImage();
          bitmap.BeginInit();
          bitmap.UriSource = source;
          bitmap.CacheOption = BitmapCacheOption.OnLoad;
          bitmap.EndInit();
          return bitmap;
      }



问候



Regards


你好

试试这个:

Hello

Try this:

img.Source = null;
(new System.Threading.Thread(() =>
 {
     while (true)
     {
         try
         {
             File.Delete(path);
             MessageBox.Show("Picture Removed");
             break;
         }
         catch{}         
     }
 })).Start();



您可以在尝试删除时显示一个ProgressBar,即显示:请等待删除文件..."



You can show a ProgressBar while tring to remove, that is showing: "Please wait to remove the file..."


这是我发现的另一种将图像加载到内存中并使用的方法作为图像来源:


Here is another way I found to load an image into memory and use it as an image source:


BitmapImage image = new BitmapImage();
image.BeginInit();
Uri imageSource=new Uri("file://"+ "C:/temp/FoxLogo.png");
image.UriSource = imageSource;
image.EndInit();
img.Source = image;


这篇关于如何在WPF(C#)中清除图像控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆