【发布时间】:2021-10-13 02:25:46
【问题描述】:
我想要实现的是,当用户完成条目时,它将使用该数据来计算另一个标签。我一直在将 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”
它认为 UpdateCost_Dif=... 的行我试图将它分成两种不同的方法,但这也不起作用。我非常感谢任何帮助以了解我做错了什么。
【问题讨论】:
-
拆分为2种方法,一次用于按钮单击一种用于文本输入。两者都独立更新模型, Completed 不是命令,而是事件。所以将其绑定到事件处理程序
-
谢谢,我已经更新了我的问题,因为我在尝试将其拆分为两个函数时遇到了错误。
-
您可以绑定命令,但不能绑定事件处理程序。您可以使用 EventToCommandBehavior 将事件转换为命令。
标签: c# xamarin xamarin.forms mvvm event-handling