【问题标题】:Bind Plugin.Media fromViewModel从 ViewModel 绑定 Plugin.Media
【发布时间】:2018-12-18 18:29:03
【问题描述】:

我有一个视图模型来处理 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> 

【问题讨论】:

  • 你说这段代码有效吗?那么问题出在哪里?
  • 它只适用于 XAML 文件后面的代码,我可以在其中引用图像控件的 x:Name。它在视图模型中不起作用。
  • 我假设我在 XAML 中没有正确的绑定属性。
  • 您的图片没有指定 x:Name
  • 对不起,我不明白(我是新手)。我认为 ViewModel 的重点是你不需要 x:Name 因为这只是为了后面的代码。您是否使用图像 x:Name 作为图像控件的绑定参考?提前致谢。

标签: mvvm xamarin.forms


【解决方案1】:

如果您想在视图模型中使用它,请将视图模型的实例分配给页面的 BindingContext,这样基本上就是您的代码隐藏中的唯一行。

public YourPage()
{
    InitializeComponent();

    BindingContext = new YourViewModel();
}

现在应该可以了。

更新

我从你的 XAML 中看到:

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

其中StreamStream 的一种类型,但您为其分配了ImageSource。你可以这样做:&lt;Image HeightRequest="150" BackgroundColor="LightGray" Source="{Binding NewImage}"&gt;

【讨论】:

  • 抱歉,我确实在 XAML 中绑定了 ViewModel,我已经更新了上面的 XAML 代码。我会试试你提到的,看看它是否有帮助。
  • 更新了答案
  • 你让我走上了正确的道路......我在上面做了,它有效。
猜你喜欢
  • 2015-03-21
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
相关资源
最近更新 更多