从 ViewModel 绑定 Plugin.Media [英] Bind Plugin.Media fromViewModel
问题描述
我有一个视图模型来处理 Plugin.Media 以从手机拍照.除非我在代码隐藏中有下面的代码(视图模型),否则图像不会显示,然后它工作正常,这打败了我学习 MVVM 的目标.我也尝试过 'FileImageSource
' 并以各种方式使用 'Source'
.'
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?
查看模型:
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>
推荐答案
如果你想从你的视图模型中使用它,将视图模型的一个实例分配给你页面的 BindingContext
,所以这基本上是代码隐藏中的唯一一行.
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();
}
现在应该可以了.
更新
从你的 XAML 我看到:
From your XAML I see:
<Image.Source>
<StreamImageSource Stream="{Binding NewImage}"/>
</Image.Source>
其中 Stream
是 Stream
的一种类型,但您要为其分配一个 ImageSource
.你可以简单地这样做:<Image HeightRequest="150" BackgroundColor="LightGray" Source="{Binding NewImage}">
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}">
这篇关于从 ViewModel 绑定 Plugin.Media的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!