图像未显示在MVVM XAML Xamarin表单上

时间:2018-10-17 20:43:39

标签: xaml xamarin mvvm xamarin.forms xamarin.android

我已经尝试了2天,但都没有成功在MVVM Xamarin表单的Xaml上显示图像。如果有人可以帮助我解决此问题,我将不胜感激。 这是我的代码:

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>

我的ViewModel

使用Plug.Media(从图库中选择图片)

我用过TapGestureRecognizer

哪个工作正常

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();

我设法以字节为单位获取图像,但是我无法显示该图像。 预先感谢您的支持。

1 个答案:

答案 0 :(得分:0)

尝试为ViewModel类实现INotifyPropertyChanged,然后向属性设置器调用PropertyChanged。喜欢,

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