我正在尝试使用
Image
在代码中设置 BitmapImage
的来源,但没有显示任何内容
这是我的代码:
xaml:
<Image x:Name="img" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Fill" />
背后代码:
var image = new BitmapImage(new Uri(@"C:\Users\XXX\Pictures\image.jpg", UriKind.Absolute));
image.DecodePixelWidth = 100;
this.img.Source = image;
这是一个权限问题。您的应用程序无权直接读取 c:\users\XXX,因此无法从该路径加载 BitmapImage。请参阅音乐、图片和视频库中的文件和文件夹
假设 c:\Users\XXX\Pictures 是当前用户的图片库,并且应用程序具有图片库功能,那么您可以获取图像文件的代理句柄并使用 BitmapImage.SetSourceAsync 加载它。
我假设您此处的代码已简化以供演示,因为图片库是以用户为中心的位置,不受应用程序的控制。应用程序通常不能假设存在硬编码的图像名称。
// . . .
await SetImageAsync("image.jpg");
// . . .
}
private async Task SetImageAsync(string imageName)
{
// Load the imageName file from the PicturesLibrary
// This requires the app have the picturesLibrary capability
var imageFile = await KnownFolders.PicturesLibrary.GetFileAsync(imageName);
using (var imageStream = await imageFile.OpenReadAsync())
{
var image = new BitmapImage();
image.DecodePixelWidth = 100;
// Load the image from the file stream
await image.SetSourceAsync(imageStream);
this.img.Source = image;
}
}
试试这个
image.Source = new BitmapImage(new Uri("ms-appx:///Assets/XXXX.bmp"));