在Metro应用程序中以编程方式设置图像源,图像不会出现

我的应用程序中有一个主页面和一个相机页面。 主页面的图像没有源设置和按钮。 如果单击该按钮,将转到相机页面。 在相机页面上,我捕获图像并将其保存在平板电脑上的图片库中,然后导航回主页面,我想将图像源设置为刚拍摄并保存在图片库中的图像。 这是我的相关代码。

MainPage.xaml中

 

MainPage.xaml.cs中

 private void img_OnLoaded(object sender, RoutedEventArgs e) { if (txtFirstName.Text != "" && txtLastName.Text != "") { try { imgResume.Source = ImageFromRelativePath(this, Windows.Storage.KnownFolders.PicturesLibrary.Path + ((App)Application.Current).candidate.FirstName + ((App)Application.Current).candidate.FirstName + "Resume.jpg"); imgResume.UpdateLayout(); } catch { imgResume.Source = ImageFromRelativePath(this, @"Assets/logo.png"); imgResume.UpdateLayout(); } btnCamera.IsEnabled = true; } } public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path) { var uri = new Uri(parent.BaseUri, path); BitmapImage result = new BitmapImage(); result.UriSource = uri; return result; } 

Camera.xaml.cs

 private async void Capture_Click(object sender, RoutedEventArgs e) { if (mediaCaptureMgr != null) { string firstName = ((App)Application.Current).candidate.FirstName; string lastName = ((App)Application.Current).candidate.LastName; string fileName = firstName + lastName + "Resume.jpg"; Windows.Storage.IStorageFile photo = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); await mediaCaptureMgr.CapturePhotoToStorageFileAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), photo); this.Frame.Navigate(typeof(BasicPersonalInfo)); } } 

MainPage.xaml文件中的img_OnLoaded方法尝试将图像源设置为我从Camera.xaml.cs中的Capture_click方法保存到图片库的图像。

我的问题是图片永远不会出现在第一页的图像上! 请帮忙!

这对于尝试解决从本地资源文件更新图像的相关问题的人也可能有帮助。

 myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content"); public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path) { var uri = new Uri(parent.BaseUri, path); BitmapImage result = new BitmapImage(); result.UriSource = uri; return result; } 

代码来自这里 。

我认为这部分是问题所在:

 var uri = new Uri(parent.BaseUri, path); 

这似乎试图从您的路径是一个完整的路径加载安装文件夹中的图像,我认为不支持在WinRT中打开文件,即使使用baseUri也不能用作Uri。

您应该做以下事情:

 var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync(((App)Application.Current).candidate.FirstName + "Resume.jpg"); var stream = await file.OpenReadAsync(); var bi = new BitmapImage(); bi.SetSource(stream); return bi;