OneWay WPF binding Trap

I'm sure you've used WPF binding. There are five BindingMode: Default, OneTime, OneWay,  OneWayToSource, and TwoWay.

OneWay is best for read-only property. But if it's not done correctly, it'll break the binding and the target won't be updated.

Here's how it's broken: call SetValue on the control to set the target directly. What happens here is that WPF will set the value of the target to the one passed in SetValue. That will overwrite the binding. Since the binding is OneWay, WPF cannot set the source, so it need to remove the binding to set the value. After that, even if the source is updated, the target sill stay the same. With that in mind, we must not throw exceptions in the setter of the source and the converter if that exists.

This is something we need to take into account when we set up OneWay binding. Always update the source, instead setting the target. If you're creating a library and set a dependency property on the control directly, you're setting the trap to your library users. This is rather difficult to debug.

Facebooktwitterredditlinkedintumblr

Leave a comment

Your email address will not be published. Required fields are marked *