Two self-updating properties in WPF MVVM

Given that you have an MVVM architecture in WPF, for example Josh Smith's examples

How would you implement two โ€œsynchronizedโ€ properties that update each other? I have a Price property and a PriceVatInclusive property in my model.

-When the price changes, I want the Vat inclusive price to be automatically "Price * 1.21".

-Vice versa, when PriceVatInclusive changes, I want the price to be "PriceVatInclusive / 1.21"

Any ideas on this?

What if your model is an Entity framework Entity? You cannot use the above approach ... no? Do you have to enter the settlement code in ViewMOdel or ...?

+4
source share
2 answers

One of the methods:

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 } 

If you can get a DependencyObject, you can use the dependency properties.

 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 } 
+4
source

Take a look at Polymod.NET . If you have the "Price" property on a domain object, you can create a model for this domain class, define the formula "PriceVat" = Price * 0.1. The model will know that PriceVat changes when the price changes, and report this to the user interface.

Your domain class doesn't even have to be INotifyable!

0
source

All Articles