Pass ImageSource to another page as parameter

143 views Asked by At

I tried to pass an ImageSource object to another page via shell navigation.

When I call

            await Shell.Current.GoToAsync($"{nameof(FullScreenImagePage)}?",
            new Dictionary<string, object>
            {
                ["TempImageSource"] = TempPhotoPoint.ExamplePicture
            });

I get the following Exception: System.InvalidCastException: 'Object must implement IConvertible.'

ExamplePicture is of type ImageSource.

The FullScreenImagePage has a viewmodel which contains

[QueryProperty(nameof(TempImageSource), nameof(TempImageSource))]

and

[ObservableProperty] ImageSource tempImageSource;

The viewmodel is linked to the page by using BindingContext. When I pass the TempPhotoPoint object instead, which contains an ImageSource, everything works fine. How is it possible to pass the ImageSource object only?

2

There are 2 answers

1
ToolmakerSteve On

I don't know why that doesn't work, but you can work around it by implementing method ApplyQueryAttributes, as shown in Process navigation data using a single method.

  • Be sure to add : IQueryAttributable to your viewmodel class declaration, so Maui knows to use that method.

  • In the method, you specify the conversion:

... class MyViewModel : IQueryAttributable
{
    ...

    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        TempImageSource = query["TempImageSource"] as ImageSource;
        OnPropertyChanged(nameof(TempImageSource));

        ... repeat for all other query parameters ...
    }
}
1
Christian Lindenblatt On

The reason for both exceptions is the same. I bound the original ImageSource earlier to an Image. By binding it, the stream is closed. When I try to rebind it in the FullScreenImagePage the closed stream causes the exceptions. When I do not bind it before, the passed ImageSource can be bound the way I described in my first post. I'll try to copy the StreamImageSource into a MemoryStream and work with it. When I find a solution for it, i'll post it here.