如何将Image绑定到刚从非app文件夹中挑选的文件?

时间:2013-04-17 18:32:27

标签: data-binding windows-runtime microsoft-metro winrt-xaml

用户从文件系统中选择图像。之后我想在页面上显示这个图像。我该怎么办?似乎图像控件无法访问已挑选的文件。我应该将其复制到应用本地存储吗?这是对的吗?

1 个答案:

答案 0 :(得分:1)

您不必复制文件。 StorageFile对象引用了存储在设备中的文件。查看MSDN上的File picker sampleAccessing files with file pickers的快速入门指南。

XAML

<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
    <Image x:Name="img" Stretch="None" />`
</Grid>

C#

private async Task SetImage()
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".gif");
    openPicker.FileTypeFilter.Add(".png");

    StorageFile file = await openPicker.PickSingleFileAsync();
    if(file != null)
    {
        BitmapImage bmp = new BitmapImage();

        using(var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            bmp.SetSource(stream);
        }
        img.Source = bmp;
    }
}