编程语言
首页 > 编程语言> > c# – 在Metro应用程序中以编程方式设置图像源,图像不会出现

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

作者:互联网

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

MainPage.xaml中

<Image  x:Name="imgResume" HorizontalAlignment="Left" Height="303" Margin="975,60,0,0" Grid.Row="1" VerticalAlignment="Top" Width="360" Stretch="UniformToFill" Loaded="img_OnLoaded"/>
<Button x:Name="btnCamera" Content="Camera" HorizontalAlignment="Left" Margin="1128,372,0,0" Grid.Row="1" VerticalAlignment="Top" RenderTransformOrigin="2.05800008773804,0.184000000357628" Height="59" Width="108" Click="Camera_Click" IsEnabled="False"/>

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;
}

代码是here.

标签:c,image,windows-runtime,winrt-xaml,imagesource
来源: https://codeday.me/bug/20190613/1232278.html