Implement INotifyProperty changed on Static Property in WPF and Silverlight

南楼画角 提交于 2019-12-03 16:54:14

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.

Right, but it's not really a static property, is it?
it's a public instance property that uses a static backing field.
In essence, you're binding to a specific instance of a class.

Sorry, but I think you're doing it wrong.
Personally, without knowing you're scenario, I'm willing to guess that a static property binding isn't really the technical solution you need.
What's the problem you're trying to work through?
Why isn't it better addressed by a normal binding to a ViewModel?
What's the use case for doing something like this?

Personally, this looks like a perfect scenario to have a ViewModel register to a singleton service, and once a singleton event is raised change ViewModel properties.

Ilya Khaprov

locks for multi-threading?

C# thread safety with get/set

Why does the property have to be static? If it was just a regular instance property, this wouldn't be an issue.

Avoid shared mutable state when possible :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!