内容简介:翻译自:https://stackoverflow.com/questions/16035300/make-wpf-image-load-async
我想加载Gravatar-Images并将它们从代码后面设置为WPF Image-Control.
所以代码看起来像
imgGravatar.Source = GetGravatarImage(email);
GetGravatarImage的样子:
BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.UriSource = new Uri( GravatarImage.GetURL( "http://www.gravatar.com/avatar.php?gravatar_id=" + email) , UriKind.Absolute ); bi.EndInit(); return bi;
不幸的是,当网络连接缓慢时,这会锁定GUI.有没有办法分配图像源,让它在后台加载图像而不阻塞UI?
谢谢!
我建议你在XAML的imgGravatar上使用Binding.在其上设置IsAsync = true,WPF将自动利用线程池中的线程来提取图像.您可以将解析逻辑封装到IValueConverter中,然后将电子邮件绑定为Source
在XAML中:
<Window.Resouces>
<local:ImgConverter x:Key="imgConverter" />
</Window.Resource>
...
<Image x:Name="imgGravatar"
Source="{Binding Path=Email,
Converter={StaticResource imgConverter},
IsAsync=true}" />
代码:
public class ImgConverter : IValueConverter
{
public override object Convert(object value, ...)
{
if (value != null)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(
GravatarImage.GetURL(
"http://www.gravatar.com/avatar.php?gravatar_id=" +
value.ToString()) , UriKind.Absolute
);
bi.EndInit();
return bi;
}
else
{
return null;
}
}
}
翻译自:https://stackoverflow.com/questions/16035300/make-wpf-image-load-async
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- SpringBoot | :异步开发之异步调用
- 改进异步封装:处理带返回值的异步调用
- 异步发展流程 —— Generators + co 让异步更优雅
- 文件系统与异步操作——异步IO那些破事
- Opencv图像处理系列(六)—— 图像梯度
- opencv笔记(2):图像剪切和图像移位
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Structure and Interpretation of Computer Programs - 2nd Edition
Harold Abelson、Gerald Jay Sussman / The MIT Press / 1996-7-25 / USD 145.56
Structure and Interpretation of Computer Programs has had a dramatic impact on computer science curricula over the past decade. This long-awaited revision contains changes throughout the text. Ther......一起来看看 《Structure and Interpretation of Computer Programs - 2nd Edition 》 这本书的介绍吧!