我试图通过MVVM中的以下简单公式计算“NetAmount”
GrossAmount + Carriage - Discount = 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}" />
ViewModel为SalesOrderViewModel
。
我不知道在哪里放置上面提到的公式,以便在更改任何文本框值时,它会导致更改NetAmount
属性。
我不是C#的新手,但我是MVVM和PropertyChanged
事件的新手,我知道有一些非常愚蠢的事情我做错了但是无法理解它。
任何帮助都将受到高度赞赏。
答案 0 :(得分:5)
由于NetAmount
是一个计算,因此在视图模型中将其建模为只读属性是有意义的。访问该属性实际上执行计算。最后一个技巧是,每当影响RaisePropertyChanged(NetAmountProperty)
的任何因素发生变化时,都会调用NetAmount
public const string GrossAmountPropertyName = "GrossAmount";
private double _grossAmount;
public double GrossAmount
{
get { return _grossAmount; }
set
{
if (_grossAmount == value)
return;
RaisePropertyChanged(GrossAmountPropertyName);
RaisePropertyChanged(NetAmountPropertyName);
}
}
public double Discount{} ... //Implement same as above
public double Carriage {} ... //Implement same as above
public const string NetAmountPropertyName = "NetAmount";
public double NetAmount
{
get { return GrossAmount + Carriage - Discount; }
}
编辑:如果您不想向RaisePropertyChanged
添加对每个影响NetAmount的属性的调用,那么您可以修改RaisePropertyChanged
,这样它也会引发PropertyChanged
事件NetAmount
属性。它会导致一些不必要的PropertyChanged
事件被提出,但会更易于维护
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName);
handler(this, new PropertyChangedEventArgs(NetAmountProperty);
}
}