Image.Source = new BitmapImage();在 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;

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

图片。Source = new BitmapImage();在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)
{
}
}

最新更新