Image.Source = new BitmapImage();在 UWP 中不起作用

Image.Source = new BitmapImage(); doesn't work in UWP

我在用 C# 读取文件时遇到问题。这是代码:

protected override void OnNavigatedTo(NavigationEventArgs EvArgs)
    {
        base.OnNavigatedTo(EvArgs);
        var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
        var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs;
        if (Args != null)
        {
            if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
            {
                var IMG = new Image();
                IMG.Loaded += IMG_Loaded;
                string FP = FArgs.Files[0].Path;
                Uri = FP;
                IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute));
                FV.Items.Add(IMG);
                PathBlock.Text = FArgs.Files[0].Name + " - Image Viewer";

                void IMG_Loaded(object sender, RoutedEventArgs e)
                {
                    IMG.Source = new BitmapImage(new Uri(Uri));
                }
            }
        }
        if (Args == null)
        {
            PathBlock.Text = "Image Viewer";
        }
    }

问题出在这部分:

IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute));

图像不会加载,即使在尝试应用程序可以在其自己的文件中访问的资源后也是如此:

IMG.Source = new BitmapImage(new Uri("ms-appx:///09.png, UriKind.RelativeOrAbsolute));

还是不行。 这仅适用于此代码:

var FOP = new Windows.Storage.Pickers.FileOpenPicker();
StorageFile F = await FOP.PickSingleFileAsync();
IRandomAccessStream FS = await F.OpenAsync(FileAccessMode.Read);
var BI = new BitmapImage();
var IMG = new Image();
await BI.SetSourceAsync(FS);
IMG.Source = BI;

遗憾的是,我不能在第一个代码示例中使用文件流或文件选择器,所以我不能像这里那样让它工作。

Image.Source = new BitmapImage(); doesn't work in UWP

问题是文件Path 属性 不用于在UWP 平台中直接设置图像源。 从你的代码中得出,看起来你用当前应用程序打开图像文件,如果你可以从 FArgs.Files 列表中获取 IStorageItem,你也可以将其转换为 StorageFile,然后通过打开文件流到 BitmapImage.

更多详细步骤请参考以下代码

protected async override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
    base.OnNavigatedTo(EvArgs);
    var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
    var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs;
    if (Args != null)
    {
        if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
        {
            var IMG = new Image();
            string FP = FArgs.Files[0].Path;
            var Uri = FP;
            StorageFile imageFile = FArgs.Files[0] as StorageFile;
            using (var stream = await imageFile.OpenReadAsync())
            {
                var bitmp = new BitmapImage();
                bitmp.SetSource(stream);
                IMG.Loaded += (s, e) => { IMG.Source = bitmp; };
            }

            RootLayout.Children.Add(IMG);
        }
    }
    if (Args == null)
    {

    }
}