6

我的界面中有这些文本框:

图片

其中 Total 和 Change 框是只读的。我的问题是,我如何执行一种方法来计算用户输入付款时的变化?

有界付款文本框是这样的:

private decimal _cartPayment;
public decimal CartPayment {
    get { return _cartPayment; }
    set { 
    _cartPayment = value;
    //this.NotifyPropertyChanged("CartPayment");
    }
}

我的 XAML 如下:

<TextBox Text="{Binding Path=CartPayment, Mode=TwoWay}" />

我的 ViewModel 已经INotifyPropertyChanged实现,但我不知道如何从这里开始

4

4 回答 4

9

这是一种 MVVM 方法,它不会破解任何属性的获取/设置:

<TextBox Text="{Binding Path=CartPayment, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="TextChanged">
         <i:InvokeCommandAction Command="{Binding ComputeNewPriceCommand}" />
      </i:EventTrigger>
   <i:Interaction.Triggers>
</TextBox>

xmlns:i作为System.Windows.Interactivityxaml
ComputeNewPriceCommand 中的命名空间,是指向您的重新计算方法的任何类型的 ICommand。

于 2013-05-23T10:00:28.147 回答
6

您可以利用 UpdateSourceTrigger。您可以修改您的代码,如

<TextBox Text="{Binding Path=CartPayment, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

和你的财产

private decimal _cartPayment;
public decimal CartPayment
{
get { return _cartPayment; }
set 
 { 
  _cartPayment = value;
  // call your required
  // method here
  this.NotifyPropertyChanged("CartPayment");
 }
}
于 2013-05-23T08:24:15.063 回答
3

您需要做的是添加到您的Binding UpdateSourceTrigger=PropertyChanged. 默认情况下,当控制失去焦点时,对象将被更新以节省时间。

于 2013-05-23T08:11:33.143 回答
1

我在我的应用程序中做了类似的事情,但计算了剩下的天数。

您可以尝试以下方法;

//Create a new class
public class ConreteAdder : IAdder
{
    public decimal Add(decimal total,decimal payment)
    {
        return total - payment; //What ever method or mathematical solution you want
    }
}

public interface IAdder
{
    decimal Add(decimal total, decimal payment);
}

然后,在您的虚拟机中,实现以下内容;

    private readonly IAdder _adder = new ConreteAdder();
    private void NumberChanged() //Call this method within the properties you want to create the mathematical equation with
    {
        Change = _adder.Add(Payment, Total); //Or whatever method you want
    }

    public event PropertyChangedEventHandler PropertyChanged2;

    private void OnResultChanged()
    {
        var handler = PropertyChanged2;
        if (handler == null) return;
        handler(this, new PropertyChangedEventArgs("Result"));
    }

然后,在您的属性中,只需调用这两种方法之一。例如;

public decimal CartPayment 
{
get { return _cartPayment; }
set 
{ 
    _cartPayment = value;
    OnResultChanged(); //propertychanged event handler called
    this.NotifyPropertyChanged("CartPayment");
}
}

在你的 xaml 中,像这样;

<TextBox Text="{Binding Path=CartPayment,UpdateSourceTrigger=PropertyChanged}" />

希望这可以帮助!:)

编辑:看看下面的链接。这可能会进一步帮助您。

于 2013-05-23T08:25:54.583 回答