我正在尝试通过 MVVM 中的以下简单公式计算“NetAmount”
GrossAmount + Carriage - 折扣 = NetAmount
我正在使用 MVVM Light Toolkit 并声明属性如下
public const string DiscountPropertyName = "Discount";
private double _discount;
public double Discount
{
get
{
return _discount;
}
set
{
if (_discount == value)
{
return;
}
_discount = value;
// Update bindings, no broadcast
RaisePropertyChanged(DiscountPropertyName);
}
}
public const string CarriagePropertyName = "Carriage";
private double _carriage;
public double Carriage
{
get
{
return _carriage;
}
set
{
if (_carriage == value)
{
return;
}
_carriage = value;
RaisePropertyChanged(CarriagePropertyName);
}
}
public const string NetAmountPropertyName = "NetAmount";
private double _netAmount;
public double NetAmount
{
get
{
_netAmount = Carriage + Discount;
return _netAmount;
}
set
{
if (_netAmount == value)
{
return;
}
_netAmount = value;
RaisePropertyChanged(NetAmountPropertyName);
}
}
public const string GrossAmountPropertyName = "GrossAmount";
private double _grossAmount;
public double GrossAmount
{
get
{
return _grossAmount;
}
set
{
if (_grossAmount == value)
{
return;
}
_grossAmount = value;
RaisePropertyChanged(GrossAmountPropertyName);
}
}
我在 XAML 中将这些属性与如下文本框绑定:
<TextBox Text="{Binding GrossAmount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding Mode=OneWay}"/>
<TextBox Text="{Binding Carriage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding Mode=OneWay}"/>
<TextBox Text="{Binding Discount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding Mode=OneWay}"/>
我将一个文本块与NetAmount
属性绑定,如下所示:
<TextBlock Text="{Binding NetAmount}" />
视图模型是SalesOrderViewModel
.
我不知道将上述公式放在哪里,以便在更改任何文本框的值时,它会导致更改NetAmount
属性。
我对 C# 并不陌生,但对 MVVM 和PropertyChanged
事件很陌生,我知道我做错了一些非常小的愚蠢的事情,但我无法理解它。
任何帮助将不胜感激。