public abstract class ViewModelBase : NotificationObject
{
//use a shared event so that any instance can propogate the event to all instances
private static event Action<string> _staticPropertyChanged;
protected static void OnStaticPropertyChanged(string propertyName)
{
if (_staticPropertyChanged != null)
_staticPropertyChanged(propertyName);
}
public ViewModelBase()
{
//when a new instance is created, we subscribe it to shared Busy Property Changed event
_staticPropertyChanged += ViewModelBase__staticPropertyChanged;
}
/// <summary>
/// Within each instance, handle the shared staticPropertyChanged event by raising the instance version of RaisePropertyChanged event
/// </summary>
void ViewModelBase__staticPropertyChanged(string propertyName)
{
RaisePropertyChanged(propertyName);
}
//example
private static Dictionary<long, string> _SomeSharedLookup;
public static Dictionary<long, string> SomeSharedLookup
{
get { return ViewModelBase._SomeSharedLookup; }
set { ViewModelBase._SomeSharedLookup = value; OnStaticPropertyChanged("SomeSharedLookup"); }
}
}
- Published on
Raising PropertyChanged Events on Static Properties
- Authors
- Name
- Craig Wardman
If you want to share data amongst all instances of a class you will naturally create some "static" variables.
This is fine, except when using the binding engine within Silverlight, as it relies on "PropertyChanged" events to notify the UI of a change to a property, but you can't raise an instance event from within a static property.
The way I solved this was to create a static event called "StaticPropertyChanged" which the static properties raise whenever they are changed. Within the constructor of the class I attach to this event (i.e. each instance attaches to the static event) and re-raise the event through the PropertyChanged event for the current instance.
In effect, every instance of the class will raise a PropertyChanged event whenever any of the static data is changed. The code is as follows: