0

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

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

  • 如果我从StandardStyles.xaml

这是我的绑定GroupedItemsPage.xaml

    <GridView
        x:Name="itemGridView"
        ItemTemplate="{StaticResource Standard250x250ItemTemplate}">

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

<DataTemplate x:Key="Standard250x250ItemTemplate">
            <Image Source="{Binding ImageUri}" ImageOpened="Image_ImageOpened"/>
</DataTemplate>

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

    private void Image_ImageOpened(object sender, RoutedEventArgs e)
    {

    }
  • 我不知道如何将 Image 框架元素的内容存储为二进制文件。
4

1 回答 1

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);
                }
            }
        }
    }
于 2012-09-16T02:22:28.653 回答