2017-02-17 52 views
0

我想正確加載一個圖像:現在正在測試對常見錯誤(即格式不正確的文件)。這是目前我用來測試事情的一個簡單的wpf應用程序。圖像DecodeFailed事件不會觸發?

public partial class MainWindow : Window 
{ 
    public MainWindow() { 
     var s = new BitmapImage(); 
     var uri = new Uri("test.txt", UriKind.RelativeOrAbsolute); //test exists but is obviously no image data 
     DownloadImageListener dl = new DownloadImageListener(s); 
     s.DecodeFailed += (sender, e) => 
     { 
      Console.WriteLine("event is performed as lambda"); 
     }; 
     s.BeginInit(); 
     s.UriSource = uri; 
     s.EndInit(); 
     Console.WriteLine(System.IO.File.Exists(uri.OriginalString)); //True! 
     Console.WriteLine(s.IsDownloading); //"False" - done loading! 
     Console.WriteLine(s.Width); //just to fail hard 
    } 
} 

class DownloadImageListener 
{ 
    private BitmapImage Img; 

    public DownloadImageListener(BitmapImage i) { 
     Img = i; 
     // Add "ListChanged" to the Changed event on "List". 
     Img.DecodeFailed += new EventHandler<ExceptionEventArgs>(ImageLoadFailed); 
    } 

    // This will be called whenever the list changes. 
    private void ImageLoadFailed(object sender, EventArgs e) { 
     Console.WriteLine("This is called when the loading failes"); 
    } 

    public void Detach() { 
     // Detach the event and delete the list 
     Img.DecodeFailed -= new EventHandler<ExceptionEventArgs>(ImageLoadFailed); 
     Img = null; 
    } 
} 

ImageLoadFailed方法不會被調用(不線被印刷也不視覺工作室觸發我放在那裏斷點)。難道我做錯了什麼」?我相信我按照msdn提供的教程?

編輯: 要排除所有潛在的其他錯誤,我上面的「isdownloading補充說:」檢查

Console.WriteLine(System.IO.File.Exists(uri.OriginalString)); 
  • 這表明「真」 我還添加了一個lambda作爲監聽器 - 如圖this page.

編輯2:

測試「所有」事件,似乎只有「陳ged「事件觸發(所以捕捉事件的代碼顯然是正確的) - 其餘事件永遠不會觸發。 - 爲什麼是這樣?

回答

0

你可以簡單地設置BitmapCacheOption.OnLoad使WPF立即加載鏡像文件,並得到一個異常時,它不能被解碼:

var bitmap = new BitmapImage(); 
try 
{ 
    bitmap.BeginInit(); 
    bitmap.UriSource = new Uri("test.txt", UriKind.RelativeOrAbsolute); 
    bitmap.CacheOption = BitmapCacheOption.OnLoad; 
    bitmap.EndInit(); 
} 
catch (Exception ex) 
{ 
    Debug.WriteLine(ex.Message); 
} 
+0

嗯,這工作 - 但似乎「迴避」的問題:因爲我們都知道從硬盤讀取是「慢」與其他任何事情相比。 - 因此,在加載的同時給用戶界面控制權是最終的選擇。 – paul23

+0

請注意,從本地文件加載BitmapImage始終是同步的。 IsDownloading屬性返回false。 「DownloadProgress」,「DownloadCompleted」或「DownloadFailed」事件都不會被觸發。顯然'DecodeFailed'也沒有被觸發。 – Clemens

0

DownloadFailed因爲它的名稱表示只有在圖像無法下載時纔會執行,並且您在註釋中聲明它存在但它不是圖像。

如果要檢測下載文件中的錯誤,請使用DecodeFailed事件。

+0

哦謝謝,但仍然沒有解決它。改變事件處理程序的構造函數,讓'Img.DecodeFailed + = new EventHandler (ImageLoadFailed);'仍然不會觸發它? – paul23