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
?