一种方法:
public class Sample : INotifyPropertyChanged
{
private const double Multiplier = 1.21;
#region Fields
private double price;
private double vat;
#endregion
#region Properties
public double Price
{
get { return price; }
set
{
if (price == value) return;
price = value;
OnPropertyChanged(new PropertyChangedEventArgs("Price"));
Vat = Price * Multiplier;
}
}
public double Vat
{
get { return vat; }
set
{
if (vat == value) return;
vat = value;
OnPropertyChanged(new PropertyChangedEventArgs("Vat"));
Price = Vat / Multiplier;
}
}
#endregion
#region INotifyPropertyChanged Members
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler ev = PropertyChanged;
if (ev != null)
{
ev(this, e);
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
如果您可以从DependencyObject派生,则可以使用依赖属性。
public class Sample : DependencyObject
{
private const double Multiplier = 1.21;
public static readonly DependencyProperty VatProperty =
DependencyProperty.Register("Vat", typeof(double), typeof(Sample),
new PropertyMetadata(VatPropertyChanged));
public static readonly DependencyProperty PriceProperty =
DependencyProperty.Register("Price", typeof(double), typeof(Sample),
new PropertyMetadata(PricePropertyChanged));
private static void VatPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Sample sample = obj as Sample;
sample.Price = sample.Vat / Multiplier;
}
private static void PricePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Sample sample = obj as Sample;
sample.Vat = sample.Price * Multiplier;
}
#region Properties
public double Price
{
get { return (double)GetValue(PriceProperty); }
set { SetValue(PriceProperty, value); }
}
public double Vat
{
get { return (double)GetValue(VatProperty); }
set { SetValue(VatProperty, value); }
}
#endregion
}