2

I've been using the MVVM pattern for a little while now and frequently run into a scenario where the value of one property depends on the value of another property. For instance, I have a control with a height and width, and I want to display the height and width on the control as a formatted string, "{height} x {width}". So I include the following properties in my view model:

public class FooViewModel : INotifyPropertyChanged { // . . . private double _width; public double Width { get { return _width; } set { if(_width != value) { _width = value; NotifyPropertyChanged("Width"); NotifyPropertyChanged("DisplayString"); // I had to remember to // do this. } } } public string DisplayString { get { return string.Format("{0} x {1}", _width, _height); } } // . . . } 

Then I bind to content of my Label to the DisplayString property, which seems a lot more convenient than using a IMultiValueConverter to convert from the Width and Height properties. The inconvenient part is that anywhere I need to NotifyPropertyChanged for "Width" or "Height", I also have to remember to notify for "DisplayString". I can think of myriad ways to automate this, to varying degrees, but my question is whether there is a standard practice that people generally use to do this under MVVM in WPF?

2

2 Answers 2

2

No there is no standard way of doing this.

You can write a base viewmodel class which has PropertyChanged helper method. It will look at the properties of class with DependsOn attribute (which also you'll create) and fire event for all the properties that depend on the updated property.

Sign up to request clarification or add additional context in comments.

Comments

1

If there are many dependencies between properties in the ViewModel, you can invoke NotifyPropertyChanged with an empty string to refresh all the elements which are bound from the View. I don't see a point in automating this.

5 Comments

Some of the getters in other properties are slow enough to cause noticeable lag so I wouldn't want to cause those to update unecessarily.
Then there is a problem in your design. Getters should be as simple as possible. In most cases, the calculations should be done outside of the getters. Event handlers are great for such calculations.
I agree with this, except I don't have control over the model part of the design.
Though, I suppose I could do something like cache all my get results, use a BackgroundWorker to do the full get, and update the results if necessary.
This is an option, but try not to fall into a place where you will spend a lot of time maintaning the cache and taking care of it to be up-to-date.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.