从图库/相机返回时设置图像源?

时间:2015-02-08 09:54:37

标签: xamarin xamarin.forms xamarin.forms.labs

我有一个图像视图我无法设置源代码。我正在使用一个按钮来执行一个TakePictureCommand,它调用TakePicture()方法(如下所示),然后设置我的源“ImageSource”。调试方法显示图像正在进入,但我从未在UI中看到它。

我可能没有正确设置Image的绑定,这就是我所拥有的:

Image avatar = new Image();
avatar.Source = ImageSource;

Button setImageBtn = new Button{ Text = "Photo" };
setImageBtn.Clicked += async (sender, e) =>
{
    string action = await DisplayActionSheet(
           "Event Photo", "Cancel", null, OPTION_CAMERA, OPTION_GALLERY);

    if(action == OPTION_CAMERA) {
        TakePictureCommand.Execute(null);
    }

    else if(action == OPTION_GALLERY) {
        SelectPictureCommand.Execute(null);
    }
};

TakePicture()

private async Task<MediaFile> TakePicture()
{
    Setup();

    ImageSource = null;

    return await _mediaPicker.TakePhotoAsync(
        new CameraMediaStorageOptions { 
            DefaultCamera = CameraDevice.Front, 
            MaxPixelDimension = 400 
    }).ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            Status = t.Exception.InnerException.ToString();
        }
        else if (t.IsCanceled)
        {
            Status = "Canceled";
        }
        else
        {
            var mediaFile = t.Result;

            ImageSource = ImageSource.FromStream(() => mediaFile.Source);

            return mediaFile;
        }

        return null;
    }, _scheduler);
}

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

以下方法对我有用:

首先,在XAML中我添加了图像视图

<Image Source="{Binding ImageSource}" VerticalOptions="Fill" HorizontalOptions="Fill"
                    Aspect="AspectFit"/>

其次,在ViewModel中,我添加了像这样的ImageSource属性:

public ImageSource ImageSource
{
    get { return _imageSource; }
    set { this.SetProperty(ref _imageSource, value); }
}

第三,在命令处理程序中:

await TakePicture ();

Forth,TakePicture()方法的代码和你写的一样。 我的设置():

if (_mediaPicker != null)
            return;
var device = Resolver.Resolve<IDevice>();
_mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;