问题
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