2012-10-12 27 views
2

我在我的wpf頁面上有一個圖像,該圖像從硬盤打開圖像文件。用於定義圖像的XAML是:如何強制圖像控制關閉它在wpf中打開的文件

<Image Canvas.Left="65" Canvas.Top="5" Width="510" Height="255" Source="{Binding Path=ImageFileName}" /> 

我使用卡利Micro和映像文件名稱與文件的該圖像控制應該顯示的名稱更新。

當圖像被圖像控件打開時,我需要更改文件。但該文件被圖像控制鎖定,我無法刪除或複製任何圖像。如何強制Image在打開文件後關閉文件,或者需要將文件複製到文件上?

我查了一下,沒有CashOptio的圖片,所以我不能使用它。

+1

後您獲取映像文件名稱。你在那裏關閉文件嗎? – Paparazzi

+0

@Blam:ImageFileName是這樣的:c:\ tmp \ testimage.jpg我不打開或關閉它自己。它是打開它而不關閉它的圖像控件。 – user1731110

+0

請參閱[這個問題和答案](http://stackoverflow.com/q/12799931/1136211)。在你的情況下,編寫一個將文件名轉換爲ImageSource的綁定轉換器是有意義的。 – Clemens

回答

4

您可以使用像下面這樣的binding converter,通過設置BitmapCacheOption.OnLoad將圖像直接加載到內存緩存中。該文件立即加載,之後不鎖定。

<Image Source="{Binding ..., 
       Converter={StaticResource local:StringToImageConverter}}"/> 

轉換器:

public class StringToImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     object result = null; 
     string uri = value as string; 

     if (uri != null) 
     { 
      BitmapImage image = new BitmapImage(); 
      image.BeginInit(); 
      image.CacheOption = BitmapCacheOption.OnLoad; 
      image.UriSource = new Uri(uri); 
      image.EndInit(); 
      result = image; 
     } 

     return result; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
}