我有一个处理Plugin.Media的视图模型,可以从手机上拍照。除非我在后面的代码中有下面的代码(视图模型(,否则图像不会显示,然后它工作得很好,这违背了我学习MVVM的目的。我还尝试过"FileImageSource
",并以各种方式使用了"Source'
">
有人能解释我做错了什么吗?
视图模型:
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
,这样这基本上是代码后面的唯一一行。
public YourPage()
{
InitializeComponent();
BindingContext = new YourViewModel();
}
现在它应该起作用了。
更新
从你的XAML我看到:
<Image.Source>
<StreamImageSource Stream="{Binding NewImage}"/>
</Image.Source>
其中Stream
是Stream
的一种类型,但您正在为其分配ImageSource
。您可以简单地执行以下操作:<Image HeightRequest="150" BackgroundColor="LightGray" Source="{Binding NewImage}">