The question is how to implement INotifyPropertyChanged
on a static property because the event you implement is not static, and cannot be called by a static property. Also, you cannot bind to a static property in Silverlight.
I've seen this question pop up an a few forums with a variety of solutions, none of which were very satisfying.
Well, I think I've found an elegant solution, but it's so simple I feel like I must be missing something.
The answer is, to write a non-static property that accesses a static variable like so:
private static double length;
public double Length
{
get
{
return length;
}
set
{
length = value;
NotifyPropertyChanged("Length");
}
}
I've tested it and it seems to work just fine. Am I missing something?
Technically, you're still not binding to a static property - you're binding to an instance of the class, which is using the static field as a backing store. This will work, to some extent, but...
There is a fundamental problem with this - If you have more than one item bound to this same backing store (which seems like something you're attempting, since you're purposefully making it static), the INotifyPropertyChanged
notifications will only happen on the instance where you are currently bound.
Say, for example, you had two UserControls, sitting side by side, both bound to a ViewModel containing this code. When control A sets this property, control B will never receive notifications (since it's A's INotifyPropertyChanged that runs), so it will appear out of sync.
If you really want to try to do something like this, you're probably better off having your backing store use a class that implements INotifyPropertyChanged, and "bubble" up the property through your ViewModel class. This way, multiple instances would all be notified correctly, and you could handle any multithreading/synchronization issues that might occur if necessary.
Alternatively, you may want to consider using a single instance property (with an instance field), inside of a Singleton. This, too, would give you shared notifications of your "static" property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With