Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement INotifyProperty changed on Static Property in WPF and Silverlight

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?

like image 323
Eric Avatar asked Dec 22 '22 07:12

Eric


1 Answers

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.

like image 92
Reed Copsey Avatar answered Dec 27 '22 23:12

Reed Copsey