在Windows 8中通过Image控件下载后,如何在本地存储映像?

Ale*_*kin 0 c# local-storage windows-8

我的Windows应用商店(也称为Windows 8)应用程序使用默认的网格应用程序模板来显示项目.其中的项目模板包括具有重叠文本信息的图像.为了减小应用程序的大小,我不存储每个项目的图像,而是将具有绝对路径(http)的Uri保存到图像所在的Web服务器.我修改了标准模板以绑定到图像Uri(我必须将Uri转换为字符串才能使其正常工作)现在每当我启动应用程序时,所有图像都会被Image控件下载并自动显示.

我现在想要的是自动保存曾经下载过的图像,并将下载图像的Uris修改为指向本地存储的图像.在这里我遇到两个问题:

  • 如果我从中绑定完整的ItemTemplate,我无法触发ImageOpened事件 StandardStyles.xaml

这是我的绑定GroupedItemsPage.xaml:

    <GridView
        x:Name="itemGridView"
        ItemTemplate="{StaticResource Standard250x250ItemTemplate}">
Run Code Online (Sandbox Code Playgroud)

绑定模板已修改为触发事件(StandardStyles.xaml):

<DataTemplate x:Key="Standard250x250ItemTemplate">
            <Image Source="{Binding ImageUri}" ImageOpened="Image_ImageOpened"/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

该Image_ImageOpened事件处理程序的代码隐藏文件(`GroupedItemsPage.xaml.cs')中定义的,但永远不会触发:

    private void Image_ImageOpened(object sender, RoutedEventArgs e)
    {

    }
Run Code Online (Sandbox Code Playgroud)
  • 我不知道如何将Image框架元素的内容存储为二进制文件.

Jen*_*SFT 6

我还必须在本地复制一些http图像; 这是我的工作代码.您应该使用internetURI ="http:// wherever-your-image-file-is"和图像的唯一名称来调用此方法.它会将图像复制到AppData的LocalFolder存储,然后返回新的本地图像的路径,您可以将其用于绑定.希望这可以帮助!

    /// <summary>
    /// Copies an image from the internet (http protocol) locally to the AppData LocalFolder.  This is used by some methods 
    /// (like the SecondaryTile constructor) that do not support referencing images over http but can reference them using 
    /// the ms-appdata protocol.  
    /// </summary>
    /// <param name="internetUri">The path (URI) to the image on the internet</param>
    /// <param name="uniqueName">A unique name for the local file</param>
    /// <returns>Path to the image that has been copied locally</returns>
    private async Task<Uri> GetLocalImageAsync(string internetUri, string uniqueName)
    {
        if (string.IsNullOrEmpty(internetUri))
        {
            return null;
        }

        using (var response = await HttpWebRequest.CreateHttp(internetUri).GetResponseAsync())
        {
            using (var stream = response.GetResponseStream())
            {
                var desiredName = string.Format("{0}.jpg", uniqueName);
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceExisting);

                using (var filestream = await file.OpenStreamForWriteAsync())
                {
                    await stream.CopyToAsync(filestream);
                    return new Uri(string.Format("ms-appdata:///local/{0}.jpg", uniqueName), UriKind.Absolute);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)