首页 > 解决方案 > 使用 MVVM 帮助器的视图模型中的 Xamarin 事件处理程序

问题描述

我想要实现的是,当用户完成条目时,它将使用该数据来计算另一个标签。我一直在将 MVVM 助手用于简单的函数(不是我需要条目值的事件处理程序),它工作得很好,所以我也想在这里使用它,但这不是必需的。

首先,我将展示一个有效的基本功能:

XAML:

<ImageButton x:Name="PlusButton" 
             Command="{Binding IncrementPrice}">

视图模型:

    public class ExistingProductPricingViewModel : BaseViewModel
    {
        public ExistingProductPricingViewModel()
        {
            IncrementPrice = new MvvmHelpers.Commands.Command(OnIncrement);
        }

    public ICommand IncrementPrice { get; }
    double price = 0.0;
    string test = "Price";

    public string PriceTest
        {
            get => test;
            set => SetProperty(ref test, value);
        }

    void OnIncrement()
        {
            price++;
            PriceTest = $"{price}";
        }

这很有效,当我使用 EventHandler 尝试需要用户输入时,我无法让它工作。我最后一个版本的尝试如下:

XAML:

<Entry x:Name="UpdatedCost"
       Completed="{Binding UpdatedCost_Dif}"/>

视图模型:

public class ExistingProductPricingViewModel : BaseViewModel
    {
      public ExistingProductPricingViewModel()
      { //this is where I get the error
       UpdatedCost_Dif = new MvvmHelpers.Commands.Command(UpdatedCost_Completed(null,null));
      }
     
       public ICommand UpdatedCost_Dif { get; }
       int current_diff = 0;
       public string json = "2";

        public int PriceDifference
        {
            get => current_diff;
            set => SetProperty(ref current_diff, value);
        }

        private void UpdatedCost_Completed(object sender, EventArgs e)
        {
            int updated = int.Parse(((Entry)sender).Text);
            current_diff = updated - int.Parse(json);
            PriceDifference = current_diff;
        }

我得到的错误是:

无法从“void”转换为“System.Action”

它与 UpdatedCost_Dif=... 相关联我试图将它分成两种不同的方法,但这也不起作用。我将非常感谢任何帮助以了解我做错了什么。

标签: c#xamarinxamarin.formsmvvmevent-handling

解决方案


如果在命令方法中传递参数,则需要添加“CommandParameter”来传递。检查此链接以获取更多信息: https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/button#using-the-command-interface


推荐阅读