3

我想通过绑定显示存储在 StorageFile 中的图片内容,但无论我尝试做什么,它似乎都不起作用。

这是我已经测试过的两种解决方案:

string img =( await CompetencesFolder.GetFileAsync(FormatImageNameToFileName(imageName))).Path;

然后通过绑定将获得的路径(文件的完整绝对路径)返回到源属性,并且:

 BitmapImage img = await LoadImage(await CompetencesFolder.GetFileAsync(FormatImageNameToFileName(imageName)));

  private static async Task<BitmapImage> LoadImage(StorageFile file)
        {
            BitmapImage bitmapImage = new BitmapImage();
            FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);

            bitmapImage.SetSource(stream);


            return bitmapImage;

        }

稍后将最终的 bitmapImage 返回到我的绑定属性。

这些方法都不起作用..

有人有想法吗?

编辑:修复

这是解决问题的代码:

BitmapImage img = new BitmapImage() { UriSource = new Uri( LOCAL_REPOSITORY.Path + "/Assets/gfx/cards/" + FormatImageNameToFileName(imageName) + ".jpg", UriKind.RelativeOrAbsolute) };

我混合了上面的 2 个示例:我从图片的绝对 URI 创建了我的 bitmapImage(LOCAL_REPOSITORY 包含对本地存储的引用ApplicationData.Current.LocalFolder:)

我仍然不明白为什么其他两种方式都失败了:我通常将我的图像直接绑定到 Uri、字符串或 BitmapImage,它可以工作..

4

1 回答 1

9

下面的代码展示了如何在应用程序中使用 loadimage 方法:创建一个空白应用程序,向主页添加一个图像和一个按钮。

    private async void  Button_Click_1(object sender, RoutedEventArgs e)
    {
        // load file from document library. Note: select document library in capabilities and declare .png file type
        string filename = "Logo.png";
        Windows.Storage.StorageFile sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);
        // load file from a local folder
        //Windows.Storage.StorageFile sampleFile = sampleFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("Assets\\Logo.png");

        BitmapImage img = new BitmapImage();
        img = await LoadImage(sampleFile);
        myImage.Source = img;
    }

    private static async Task<BitmapImage> LoadImage(StorageFile file)
    {
        BitmapImage bitmapImage = new BitmapImage();
        FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);

        bitmapImage.SetSource(stream);

        return bitmapImage;

    }
于 2013-02-15T21:38:12.017 回答