WAQS: PropertyChanged

7 reasons to use WAQS

WAQS documentation

 

PropertyChanged logic

Imagine that you want to calculate OrderDetail amount and Order total.

So, using WAQS, you write the following two methods in specifications to generate Amount and Total calculated properties, as I explained in my first post about calculated properties.

public static double GetAmount(this OrderDetail od)
{
    return (double)od.UnitPrice * od.Quantity * (1 - od.Discount);
}


public static double GetTotal(this Order o)
{
    return o.OrderDetails.Sum(od => GetAmount(od));
}


 



PropertyChanged issue



In MVVM, when you want to refresh UI controls bound on Models or ViewModels properties, you have to use the PropertyChanged logic.



So you have to implement INotifyPropertyChanged interface on your Models and ViewModels. This interface just contains a PropertyChanged event. This event is used by technologies such as WPF, W8, WP8 to notify the UI when bound property is modified and UI control has to be refreshed.



In our case, to refresh the control bound on Amount when UnitPrice, Quantity or Discount changed, we have to raise a PropertyChanged event with "Amount" as parameter for properties UnitPrice, Quantity and Discount. With this way, if the user change one of these three properties, Amount will be automatically refreshed.



For Total, we have to add handler on each OrderDetail.PropertyChanged in order to raise a PropertyChanged with "Total" as parameter if one of the OrderDetails Amount changed. In addition, we have to add handler on OrderDetails.CollectionChanged in case the user add (or remove) an OrderDetails.



What a pain! In addition, this is bad for maintainability because, if you want to change the way to calculate the Order Total, you have to change PropertyChanged logic too.



For this reason, I think that this way is not a good pattern IMHO.



 



How does WAQS fix it?



WAQS analyzes specification methods using Roslyn to create the property. Based on this analyze, WAQS can determine the calculated properties dependencies.



So all the code we had to write is generated by WAQS. With this way you have no pain to write it and if you change your specification method, you just have to regenerate your T4 template to fix the PropertyChanged logic.

This entry was posted in 16402, 16868, 18343, 18344, 8708. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>