使 WPF 图像加载异步 [英] Make WPF Image load async
问题描述
我想加载 Gravatar-Images 并将它们从代码隐藏到 WPF Image-Control.所以代码看起来像
I would like to load Gravatar-Images and set them from code behind to a WPF Image-Control. So the code looks like
imgGravatar.Source = GetGravatarImage(email);
GetGravatarImage 的样子:
Where GetGravatarImage looks like:
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.有没有办法分配图像源并让它在后台加载图像而不阻塞用户界面?
Unfortunately this locks the GUI when the network connection is slow. Is there a way to assign the image-source and let it load the image in the background without blocking the UI?
谢谢!
推荐答案
我建议您使用 XAML 中的 imgGravatar 绑定.在其上设置 IsAsync=true,WPF 将自动利用线程池中的线程来拉取您的图像.您可以将解析逻辑封装到 IValueConverter 中,并将电子邮件绑定为 Source
I suggest you to use a Binding on your imgGravatar from XAML. Set IsAsync=true on it and WPF will automatically utilize a thread from the thread pool to pull your image. You could encapsulate the resolving logic into an IValueConverter and simply bind the email as 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;
}
}
}
这篇关于使 WPF 图像加载异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!