0
votes

I have tried unsuccessfully for 2 days to display image on my Xaml from MVVM Xamarin forms. I would appreciate if someone could help me with this issue. Here is my code:

XAML

<Grid>
    <Grid.RowDefinitions>
         <RowDefinition Height="*" />
         <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
         <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
     <Image Source="{Binding GetImageSource}"  Grid.Column="0" Grid.Row="0" HorizontalOptions="Center" />
       <Image Source="camera.png" HorizontalOptions="Center" Grid.Column="0" Grid.Row="1">
       <Image.GestureRecognizers>
           <TapGestureRecognizer Command="{Binding TakePhoto}" />
       </Image.GestureRecognizers>
     </Image>
</Grid>

My ViewModel

Using Plugin.Media (Choose image from gallery)

I've used TapGestureRecognizer

Which is working fine

private ImageSource imageSource { get; set; }

public ImageSource GetImageSource
{
    get { return imageSource; }
    set
    {
        imageSource = value;
    }
}

if (!CrossMedia.Current.IsPickPhotoSupported)
{
    var message = "Picking image is not supported";
    DependencyService.Get<IMessage>().ShortAlert(message);
    return;
}
var files = await CrossMedia.Current.PickPhotoAsync();
if (files == null)
    return;

GetImageSource = ImageSource.FromStream(() =>
{
    var stream = files.GetStream();

    return stream;
});
var ms = new MemoryStream();
files.GetStream().CopyTo(ms);
files.Dispose();
imgAsBytes = ms.ToArray();
ms.Dispose();

I have managed to get the image in byte which is fine, but I can't display the image. Thanks in advance for your support.

1
does your VM implement INotifyPropertyChanged? - Jason

1 Answers

0
votes

Try implementing INotifyPropertyChanged for your ViewModel class and invoke PropertyChanged to your property setter. Like,

public event PropertyChangedEventHandler PropertyChanged;
public ImageSource GetImageSource
{
    get { return imageSource; }
    set
    {
        imageSource = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(GetImageSource)));
    }
}