WPF MVVM and calculated properties
Today I have to solve a situation like this one
I have a ViewModel, with a property of type X, and has a property called BorderBrush that is calculated based on a property Rank of X class. Building such a property is straighforward, but I need to put some logic inside the Viewmodel to monitor when the Property Rank is changed on X class to notify the interface that the property BorderBrush (that depends on Rank property of X) is also changed.
Thanks to some base classes of my friend Mauro, that make an idea raise in my mind, I decided to solve this situation with an helper that permits me to use Strongly Typed Syntax.
|
|
With the PropertyLink I’m able to express the fact that two object are related, and when certain property of object _rilevazione changed, another object should raise a property changed. The first link tells my system that whenever the property Rank changed I need to raise a propertyChanged event by the current object telling that BackGroundBrush property is also changed.
To make this possible I created a new interface.
|
|
This is needed to make possible from another object to tell ViewModel: Hey raise a property changed for property x. The object that implement this is really simple
|
|
It keeps two weak reference for the originator of the event and the source of related events, and in the constructor simply handle the ProppertyChanged event for the originator event.
|
|
The HandlePropertyChanged simply looks into a internal dictionary if the property of the originator has some links, and for each linked property it tells the source object to raise the corresponding related property. The link Function is where everything takes place, thanks to a little bit of ExpressionTree knowledge.
|
|
The GetMemberName() extension method is this, and is taken from Mauro’s Radical.
|
|
Now I can use strongly typed syntax to express a link between properties of my View Models, with few lines of code.
alk.