An easy way to update all the UI Property Bindings of an Instance at once! – Silverlight and WPF

Imagine that you have a lot of properties in a class and you are very sure that all of those properties are getting updated at the same point of time. What generally we do in the ViewModel scenario is that we create Property setters for all these and raise PropertyChanged event so as to get the data reflected in the UI layer bindings. But that is a real resource waste when you really know the time of all your property updates. The solution is really easy as per the MSDN documentation for PropertyChanged Event in the remarks section it says “The PropertyChanged event can indicate all properties on the object have changed by using either a null reference (Nothing in Visual Basic) or String.Empty as the property name in the PropertyChangedEventArgs.” It seems that this is a great saver in terms of code writing and execution, since we need to raise only one PropertyChanged Event per class just after the property updation.

Think about a Stock Trading scenario as an example to this, you must have a Quote class which generally will have lot of properties in it, and there will be an Update method on a timer may update this quote object. Imagine that this class is bound to a DataTemplate at XAML level.

    public class Quote : ViewModelBase
{
public string Symbol { get; set; }
public double Last { get; set; }
public double Change { get; set; }
public double Bid { get; set; }
public double Ask { get; set; }
public double Open { get; set; }
public string Percentage { get; set; }
public double Volume { get; set; }

public bool IsRefreshed
{
get { return _isRefreshed; }
set
{
_isRefreshed = value;
RaisePropertyChanged(null);
}
}
private bool _isRefreshed;
}

Isn't the code very neat with the awesome Auto-Implemented Properties rather than having fields and expanded setters with RaiseProertyChanged in all those?. Now in the Stock Update method you can set all these properties and set IsRefreshed=true which in turn calls RaisePropertyChanged(null) and makes the WPF/Silverlight binding infrastructure to re-evaluate all the bindings associated with the UI.

I recommend using the MVVM implementation by Josh Smith for the basic ViewModel architecture. You can download his MVVM Foundation from codeplex - http://mvvmfoundation.codeplex.com/

Comments

Popular posts from this blog

Time Picker User Control

A simple Multiselect ComboBox using expression Blend

A Simple Radial Panel for WPF and SilverLight