图像DecodeFailed事件未触发?

时间:2017-02-17 01:15:51

标签: c# wpf image events

我正在尝试正确加载图片:现在针对常见错误(即格式错误的文件)进行测试。它是我用来测试事物的一个简单的wpf应用程序。

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:

测试“所有”事件似乎只有“已更改”事件触发(因此捕获事件的代码显然是正确的) - 其余事件永远不会触发。 - 这是为什么?

2 个答案:

答案 0 :(得分:0)

DownloadFailed因为它的名称表示只有在无法下载图像时执行,并且在评论中说明它存在但不是图像。

如果要检测下载文件中的错误,请使用DecodeFailed事件。

答案 1 :(得分: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);
}