I was answering another question about creating a binding in code-behind, and my original attempt at answering it was to post binding code that didn’t specify a Path. This binding compiles fine, however the value is never updated. If I change the binding to use a Path, it works fine.
Why is this? And what is the correct way to create a binding in code-behind that doesn’t have a Path? For example, how would I recreate Value="{Binding }" in code-behind?
Non-Working code:
Binding b = new Binding();
b.Source = SomeInt;
b.Mode = BindingMode.OneWay;
MyProgressBar.SetBinding(ProgressBar.ValueProperty, b);
SomeInt = 50;
Working code:
Binding b = new Binding();
b.Source = this;
b.Path = new PropertyPath("SomeInt");
MyProgressBar.SetBinding(ProgressBar.ValueProperty, b);
SomeInt = 50;
The binding engine subscribes to INPC and DP-changes on the
Sourceobject (and non-leaves on thePath), and checks whether thePathproperty/properties was/were changed. If there is noPaththere are no notifications. A rather unfortunate drawback.(I might be oversimplifying the system a bit but the essence is that there are no updates to source-changes, they are not and cannot be monitored)
{Binding}is equivalent tonew Binding()(no additional properties), this binding may update as there are events forDataContextchanges.