我正在为Win 8.1(WinRT)做一个Windows应用商店应用。该应用程序的其中一个页面是地址簿。在某些情况下,应用会收到推送通知。其中一个可能是某个联系人有一个新的图片。当应用程序处理推送通知(不是推送通知的后台任务,工作正常)时,它会从推送通知中指定的链接下载新图像,并触发应该使用新图像更新UI的事件。图像存储在LocalFolder(ApplicationData.Current.LocalFolder)中。触发事件后,UI会更新,但现在没有相应联系人的任何图片。重新启动应用程序后,将显示图片。当应用程序运行时,我还打开了Windows资源管理器以查看文件是否已下载。一个奇怪的事情是,在应用程序重新启动(或停止)之前,新图片没有缩略图。我真的无法弄清楚为什么我需要重新启动应用程序才能显示图片。图像非常小,约为40-60KB。通过重置绑定到引发PropertyChanged的属性的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,它是ListView(duh)的DataTemplate:
<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;
}
非常感谢你的帮助!
答案 0 :(得分:0)
事实证明,将文件保存到文件系统的方法创建了某种句柄,这样就不允许应用加载图像。我所做的是改变保存文件的方法。
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);