我在 WPF 窗口中有一个图像控件,它的 xmls 如下:
  <Image Source="{Binding Path=ImageUrl,Converter={StaticResource ImageSourceConverter}}"
        Height="150" HorizontalAlignment="Left" Margin="100,15,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" />
在运行时,我通过更改有界属性的值来更改 Image 的来源。此代码在正常情况下工作正常。只有在断开互联网连接后才会出现问题。如果下载图像时断开连接,则不会显示图像。没关系。但是当互联网恢复并且图像源更改为另一个图像 url 时,图像不会被下载。ImageConverter 甚至没有被调用。在此之后,无法在控件中显示图像。图像控制卡住。
public class ImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string url;
        try
        {
            if (value is string)
                url = (string)value;
            else
                url = ((Uri)value).AbsolutePath;
        }
        catch (Exception)
        {
            url = string.Empty;
            return value;
        }
        BitmapImage src = new BitmapImage();
        if (targetType == typeof(ImageSource))
        {
            if (value is string)
            {
                string str = (string)value;
                src.BeginInit();
                src.CacheOption = BitmapCacheOption.OnLoad;
                src.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                src.UriSource = new Uri(str, UriKind.RelativeOrAbsolute);
                src.EndInit();
                return src;
            }
            else if (value is Uri)
            {
                Uri uri = (Uri)value;
                return new BitmapImage(uri);
            }
        }
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
任何帮助将不胜感激。