Let’s say in some abstract ViewModel base-class I have a plain-old property as follows:
public Size Size
{
get { return _size; }
set
{
_size = value;
OnPropertyChanged("Size");
}
}
I then create a more specific ViewModel, inheriting from the previous one, which contains the following property:
public Rect Rectangle
{
get { return new Rect(0, 0, _size.Width, _size.Height); }
}
Now, in some View class I bind to the aforementioned ViewModel’s Rectangle property. Everything works fine, until I change the size. When Size changes, Rectangle doesn’t know about it and the change doesn’t propagate to the View. And since Rectangle is in the child class, I can’t simply add an OnPropertyChanged("Rectangle") to the Size setter.
Now imagine that I have many different properties like Rectangle, that all depend on base-class properties, and that none of these changes are being propagated. I need some lightweight and elegant way of chaining change notifications, preferably one that doesn’t require a lot of code and doesn’t force me into using dependency properties.
Obviously there are a lot of ugly solutions here- what I am looking for is something clean and clever. It seems to me this would be a very common scenario, and it seems to me there might be an MVVM-friendly way of doing this.
I recently blogged about this exact problem. I include a
[DependsUpon("Size")]attribute with the Rectangle. I REALLY like this approach, because it keeps the dependency knowledge with the code that creates the dependency, not the other way around.Take a look: http://houseofbilz.com/archive/2009/11/14/adventures-in-mvvm—-dependant-properties-with-inotifypropertychanged.aspx