Search code examples
c#winrt-xamlwindows-phone-8.1winrt-async

How to get list of photos to a ListElement of a xaml page?


I m building a windows phone 8.1 application and using WinRT I need to capture a photo from my and need to display the captured photos as a list. I written the following code but I am unable to run it and I'm getting errors. Can any1 please correct this ?

Code:

private async void BtnCapturePhoto_Click(object sender, RoutedEventArgs e)     
{         
    BtnCapturePhoto.IsEnabled = false;

    var photoStorageFile = await cameraCapture.CapturePhoto();         
    var bitmap = new BitmapImage();

    await bitmap.SetSourceAsync(await photoStorageFile.OpenReadAsync());

    PhotoListView.Items.Add(bitmap);
    BtnCapturePhoto.IsEnabled = true;       
}

Errors:

Following are the errors when I run the application:

Error1

The best overloaded method match for 'Windows.UI.Xaml.Media.Imaging.BitmapSource.SetSourceAsync(Windows.Storage.Streams.IRandomAccessStream)' has some invalid arguments

Error2

Argument 1: cannot convert from 'void' to 'Windows.Storage.Streams.IRandomAccessStream' 

Error3

'object' does not contain a definition for 'OpenReadAsync' and no extension method 'OpenReadAsync' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) 

Solution

  • The problem is that photoStorageFile is a System.Object type in your code but it's a StorageFile in reality, so we first need to downcast it.

    // Get the photoStorageFile as StorageFile not System.Object
    StorageFile photoStorageFile = await cameraCapture.CapturePhoto() as StorageFile;
    
    // Now we can properly set the source of the bitmapImage
    using (IRandomAccessStream fileStream = await photoStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
    {
         // Set the image source to the selected bitmap
         BitmapImage bitmapImage = new BitmapImage();
    
         await bitmapImage.SetSourceAsync(fileStream);
         bitmap.Source = bitmapImage;
    }
    

    this code should work