Bind Plugin.Media fromViewModel

本小妞迷上赌 提交于 2021-01-29 12:37:44

问题


I have a view model that handles the Plugin.Media to take a picture from the phone. The image will not show unless I have the code below (View Model) in the code-behind, then it works fine, which is defeating the object of me learning MVVM. I have also tried 'FileImageSource' and used 'Source' in its various ways.'

Can anyone explain what I am doing wrong?

View Model:

public string FilePath { get => _filepath; set { _filepath = value; OnPropertyChanged(); } }
private string _filepath;

public Command CaptureImage
    {
        get
        {
            return new Command(TakePicture);
        }
    }

//

private async void TakePicture()
{
        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            //say something
            return;
        }

        var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
        {
            Directory = "FoodSnap",
            Name = GetTimestamp(DateTime.Now),
            PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom,
            CustomPhotoSize = 50
        });

        if (file == null)
            return;

        FilePath = file.Path;            

}

XAML:

<pages:PopupPage
    xmlns:pages="clr- 
    namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:vm="clr-namespace:TacticalFitness.ViewModels"
    x:Class="TacticalFitness.Views.PopUps.AddFoodSnapPopUp">

<BindableObject.BindingContext>
    <vm:AddSnapViewModel/>
</BindableObject.BindingContext>
<StackLayout>
        <Image Source="{Binding FilePath}" HeightRequest="150" BackgroundColor="LightGray" >
           <Image.GestureRecognizers>
                <TapGestureRecognizer
                    Command="{Binding CaptureImage}"
                    NumberOfTapsRequired="1" />
            </Image.GestureRecognizers>
        </Image>
</StackLayout>
</pages:PopupPage> 

回答1:


If you want to use this from your view model, assign an instance of the view model to the BindingContext of your page, so that is the only line in your code-behind basically.

public YourPage()
{
    InitializeComponent();

    BindingContext = new YourViewModel();
}

Now it should work.

Update

From your XAML I see:

<Image.Source>
    <StreamImageSource Stream="{Binding NewImage}"/>
</Image.Source>

Where Stream is a type of Stream but you are assigning an ImageSource to it. You can simply do this: <Image HeightRequest="150" BackgroundColor="LightGray" Source="{Binding NewImage}">



来源:https://stackoverflow.com/questions/51273203/bind-plugin-media-fromviewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!