WinRT 映像 XAML 下载后不会加载
本文关键字:加载 下载 映像 XAML WinRT | 更新日期: 2023-09-27 18:32:43
我正在为Win 8.1(WinRT(开发Windows应用商店应用程序。该应用程序的一页是地址簿。在某些情况下,应用会收到推送通知。其中之一可能是某个联系人有了新的图片。当应用处理推送通知(不是推送通知的后台任务,工作正常(时,它会从推送通知中指定的链接下载新图像,并触发应使用新图像更新 UI 的事件。图像存储在 LocalFolder (ApplicationData.Current.LocalFolder( 中。触发事件后,UI 将更新,但现在没有相应联系人的任何图片。重新启动应用程序后,将显示图片。在应用程序运行时,我还打开了Windows资源管理器以查看文件是否已下载以及是否已下载。一个奇特的事情是,在应用程序重新启动(或停止(之前,新图片没有缩略图。我真的不知道为什么我需要重新启动应用程序才能显示图片。图像非常小,约为 40-60KB。更新是通过重置绑定到引发属性更改的属性的 ItemsSource 来实现的。可以看出,由于短暂的闪烁,设置了 ItemsSource,但现在更新的项目没有图片。
以下是执行下载的代码:
public async Task GetContactImage(String[] pushContent)
{
var folder = ApplicationData.Current.LocalFolder;
var contactImagesfolder = await folder.CreateFolderAsync("ContactImages", CreationCollisionOption.OpenIfExists);
HttpClient httpClient = new HttpClient();
// Increase the max buffer size for the response so we don't get an exception with so many web sites
httpClient.MaxResponseContentBufferSize = 256000;
HttpResponseMessage response = await httpClient.GetAsync(pushContent[2]);
StorageFile picture = await contactImagesfolder.CreateFileAsync(pushContent[2].Split('/').Last(), CreationCollisionOption.ReplaceExisting);
IRandomAccessStream pictureStream = await picture.OpenAsync(FileAccessMode.ReadWrite);
DataWriter writer = new DataWriter(pictureStream.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await pictureStream.FlushAsync();
pictureStream.Dispose();
writer.Dispose();
Dal.Instance.UpdateContactImage(pushContent[1], pushContent[2]);
}
相应的 XAML,它是列表视图 (duh( 的数据模板:
<Image Height="128" Width="128" Source="{Binding Converter={StaticResource contactImageConverter}}" />
以及我用来设置 Source 属性的转换器:
public object Convert(object value, Type targetType, object parameter, string language)
{
var contact = value as Contact;
String imagePath = "ms-appx:///Assets/UnknownMan.png";
if (contact != null)
{
if (contact.Image != null && contact.Image != "" && contact.Image != "Unknow_man.png")
{
imagePath = "ms-appdata:///local/ContactImages/" + contact.Image.Split('/').Last();
}
}
return imagePath;
}
非常感谢您的帮助!
事实证明,将文件保存到文件系统的方法创建了某种句柄左右,这将不允许应用程序加载图像。我所做的是改变保存文件的方法。
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFolder contactImagesfolder = await folder.CreateFolderAsync("ContactImages", CreationCollisionOption.OpenIfExists);
StorageFile picture = await contactImagesfolder.CreateFileAsync(imageURL.Split('/').Last(), CreationCollisionOption.FailIfExists);
HttpClient httpClient = new HttpClient();
// Increase the max buffer size for the response so we don't get an exception with so many web sites
httpClient.MaxResponseContentBufferSize = 256000;
HttpResponseMessage response = await httpClient.GetAsync(imageURL);
var responseByteArray = await response.Content.ReadAsByteArrayAsync();
await FileIO.WriteBytesAsync(picture, responseByteArray);
Dal.Instance.UpdateContactImage(contactID, imageURL);