c# - 在项目 C# Windows 应用商店应用程序之外添加图像

标签 c# windows-8 windows-runtime fileopenpicker

在我的 xaml 文件中,我有一个名为 OutputImg 的图像。 我还有一个名为 OutputTB 的文本 block ,用于显示图像的名称,还有一个按钮,可让我从“图片”文件夹中选择图像。

隐藏代码:

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = Picker.ViewMode.List;
    openPicker.SuggestedStartLocation = PickerLocationId.PicutresLiibrary;
    openPicker.FileTypeFilter.Add(".png");
    StorageFile.file = await openPicker.PickSingleFileAsync();
    OutputTB.text = file.Name;


    BitmapImage image = new BitmapImage(new Uri(file.path));
    OutputImg.Source = image;
}

问题是,即使我没有收到任何错误,我的图片也不会显示。它将图片的名称写入 OutputTB.text,但 Image 仍为空。如何使我选择的图像出现在 OutputImg 图像框中。

我知道我在这里可能缺少一个非常基本的东西,但这只是一个学习项目

最佳答案

您不能使用 file.path 为位图创建 Uri 对象,因为 file.path 提供旧式路径(例如 c:\users\...\foo.png)。位图需要新样式的 uri 路径(例如 ms-appdata:///local/path..to..file.../foo.png)。

但是,据我所知,没有任何方法可以为图片库指定新样式 uri 路径。因此,您必须使用一个简单的解决方法:

由于您拥有对该文件的引用,因此您可以访问该文件的流,然后将该流设置为位图的源:

StorageFile file = await openPicker.PickSingleFileAsync();
OutputTB.text = file.Name;

// Open a stream for the selected file.
var fileStream =
    await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

// Set the image source to the selected bitmap.
BitmapImage image = new BitmapImage();
image.SetSource(fileStream);

OutputImg.Source = image;

关于c# - 在项目 C# Windows 应用商店应用程序之外添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15623656/

相关文章:

mvvm - Caliburn Micro 和跨应用程序共享 View 模型

windows-8 - WinRT/Metro 应用程序限制如何实现?

c# - Windows 8 将属性属性名称绑定(bind)到 UI

c# - 处理文本框中的 Shift-Enter 事件

c# - SqlDataReader 在项目之间的行为不同

windows-8 - WinJS getPrincipalNameAsync

c# - 可以为纵向和横向指定两种不同的布局吗?

c# - Winrt蓝牙错误

c# - ssis 脚本任务中的字符数据中不允许使用 ']]>'

c# - 从控制台应用程序异步调用 Azure 移动服务