Захват и обновление источника изображения с использованием MVVM в Xamarin - PullRequest
0 голосов
/ 16 октября 2018

Я пытаюсь сделать снимок и отобразить захваченное изображение в Xamarin, но изменение привязки источника изображения, похоже, не работает.Это кажется очень простым, поэтому я не совсем уверен, где я ошибаюсь.

MainPageViewModel.cs

public class MainPageViewModel : ViewModelBase
{

    private string _imageSource;
    public string ImageSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            SetProperty(ref _imageSource, value);
        }
    }

    public DelegateCommand TakePhotoCommand { get; private set; }

    public MainPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService)
        : base(navigationService)
    {
        Title = "Main Page";

        _dialogService = pageDialogService;

        TakePhotoCommand = new DelegateCommand(TakePhoto);

    }


    async void TakePhoto()
    {

        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await _dialogService.DisplayAlertAsync("No Camera", ":( No camera avaialble.", "OK");

            return;
        }


        var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
        {
            PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
            Directory = "Sample",
            Name = "test.jpg"
        });

        if (file == null)
            return;

        // This does get called ok
        ImageSource = file.Path;

    }
}

ViewModelBase.cs

public class ViewModelBase : BindableBase, INavigationAware, IDestructible
{
    protected INavigationService NavigationService { get; private set; }

    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    public ViewModelBase(INavigationService navigationService)
    {
        NavigationService = navigationService;
    }

    public virtual void OnNavigatedFrom(NavigationParameters parameters)
    {

    }

    public virtual void OnNavigatedTo(NavigationParameters parameters)
    {

    }

    public virtual void OnNavigatingTo(NavigationParameters parameters)
    {

    }

    public virtual void Destroy()
    {

    }
}

MainPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PhotoTesting.Views.MainPage"
             Title="{Binding Title}">

    <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
        <Image Source="{Binding ImageSource}" WidthRequest="200" HeightRequest="200" Aspect="AspectFill" />
        <Button x:Name="CameraButton" Text="Take Photo" Command="{Binding TakePhotoCommand}" />
    </StackLayout>

</ContentPage>

Я знаю, что бит захвата изображения работает нормально, проблема, похоже, заключается в установке image.source послестраница загружена.

1 Ответ

0 голосов
/ 20 декабря 2018

Вам необходимо связать Источник Изображение с ImageSource в MainPage.xaml
Объект ImageSource может быть получен из потока файлов.Вот код:

public class MainPageViewModel : ViewModelBase
{
    private ImageSource _imageSource;
    public ImageSource ImageSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            SetProperty(ref _imageSource, value);
        }
    }

    public DelegateCommand TakePhotoCommand { get; private set; }

    public MainPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService)
        : base(navigationService)
    {
        Title = "Main Page";

        _dialogService = pageDialogService;

        TakePhotoCommand = new DelegateCommand(TakePhoto);

    }

    async void TakePhoto()
    {
        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await _dialogService.DisplayAlertAsync("No Camera", ":( No camera avaialble.", "OK");

            return;
        }

        var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
        {
            PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
            Directory = "Sample",
            Name = "test.jpg"
        });

        if (file == null)
            return;

        // Here is the problem
        //ImageSource = file.Path;

        // This is the fix
        ImageSource = ImageSource.FromStream(() => file.GetStream());
    }
}
...