如何在C#和Xaml中将字符串URL添加到图像源

3
我有一个字符串数组,其中包含图像的URL。
数组中的示例图像:
string Image = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/187738_100000230436565_1427264428_q.jpg";

现在我需要在Xaml中绑定图片。
<Image Name="img" HorizontalAlignment="Left" VerticalAlignment="Top" Width="66" Height="66" Source="{Binding Image} " />

尝试提供img.source,但由于无法将字符串实现为system.windows.media.imagesource而不被接受。

如果您正在绑定,可以使用字符串。字符串(url)存储在哪里?Image控件的DataContext是什么? - Shawn Kendrot
1个回答

5

你尝试设置Source了吗:

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri("https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/187738_100000230436565_1427264428_q.jpg");;
bitmapImage.EndInit();

img.Source = bitmapImage;

这里有更多相关的信息。

编辑

对于远程图片,可能无法使用此方法(目前无法测试),在这种情况下,您需要下载图像,以下是如何操作:

var imgUrl = new Uri("https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/187738_100000230436565_1427264428_q.jpg");
var imageData = new WebClient().DownloadData(imgUrl);

// or you can download it Async won't block your UI
// var imageData = await new WebClient().DownloadDataTaskAsync(imgUrl);

var bitmapImage = new BitmapImage {CacheOption = BitmapCacheOption.OnLoad};
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(imageData);
bitmapImage.EndInit();

return bitmapImage;

是的,我尝试了这个,出现了相同的错误字符串到system.windows.media.imagesource错误。 - Satti
@SriramSatti 如果远程图片无法使用此方法,请尝试另一种方法。 - Dimitar Dimitrov
1
感谢您的回复...我用一行代码得到了它 img.Source = new BitmapImage(new Uri("https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/187738_100000230436565_1427264428_q.jpg", UriKind.RelativeOrAbsolute)); - Satti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接