让WPF图像加载异步 [英] Make WPF Image load async
问题描述
我想加载的gravatar的图像和code设置他们背后一个WPF图像控制。
因此,code看起来像
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。是否有指定图像源,让它在后台加载图像,而不阻塞UI的方式?
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?
谢谢!
推荐答案
我建议你使用你的imgGravatar从XAML绑定。将 IsAsync = TRUE 它和WPF会自动使用来自线程池中的线程来拉你的形象。你可以封装解决逻辑成的IValueConverter,只是绑定的电子邮件源
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}" />
在code:
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屋!