WPF Image 控件绑定时报 无法从流中读取 的错误

Image 控件绑定时报 无法从流中读取 的错误

发现是图片有问题,参考网上使用 HttpWebRequest 的检测方法,结合发现问题图片的 PropertyItems 为空(不确定能不能作为判断依据)。

个人示例:

// 检测图片有效性;
foreach (医院列表信息 info in res.data)
{
    if (string.IsNullOrEmpty(info.hospitalPicture))
    {
        continue;
    }
 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(info.hospitalPicture);
    WebResponse response = request.GetResponse();
    Image img = Image.FromStream(response.GetResponseStream());
 
    if (img.PropertyItems.Length == 0)
    {
        Logger.Net.Debug($"[选择医院]该医院({info.hospitalName})图片无法解析,将使用默认图");
        ShowAlert(false, "图片解析出错", $"{info.hospitalName} 的图片无法解析,将使用默认图,请联系相关人员换图");
        info.hospitalPicture = "";
    }
}
 
var buttons = res.data.Select(x => new HospitalButtonInfo()
{
    Name = x.hospitalName,
    HospitalId = x.hospitalId,
    Order = x.hospitalId == FrameworkConst.HospitalId ? 1 : 2,
    IsEnabled = true,
    ImageSource = string.IsNullOrEmpty(x.hospitalPicture) ? ResourceEngine.GetImageResource("虚拟医院_House") : new BitmapImage(new Uri(x.hospitalPicture, UriKind.Absolute))
}).ToList();
 
Data = buttons;


另外,出错应该是构造 BitmapImage 后就产生的,而不是控件绑定数据时产生的,因为把 foreach 那段放在构建 buttons 后面还是会出错,这也说明构造 BitmapImage 有延迟?就是说即使之后给 ImageSource 重新赋值,之前的 BitmapImage 构建还是会运行。

阅读 3.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进