3

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; 

2 Answers 2

3

The binding engine subscribes to INPC and DP-changes on the Source object (and non-leaves on the Path), and checks whether the Path property/properties was/were changed. If there is no Path there 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 to new Binding() (no additional properties), this binding may update as there are events for DataContext changes.

Sign up to request clarification or add additional context in comments.

9 Comments

That's probably true too: INPC says which property changed. There's no mechanism to say "the whole object changed".
@JoeWhite However I can set my binding to nothing ({Binding }), and the PropertyChange notification works just fine. Isn't there a way to do that in code-behind?
@Rachel: That is because there are notifications for the DataContext changes, that is an exception to the rule though.
@H.B. Could you suggest the code-behind syntax which would be the equivalent to {Binding }?
@Rachel: That's just new Binding(), no source no path, nothing else.
|
1

Binding.Source is typed as System.Object. So when you do:

b.Source = SomeInt; 

you're assigning a value type (System.Int32) into something of type System.Object, which means you'll get a boxed copy of the original value.

The boxed copy lives on the heap and has no relation to the original variable. When you modify the original variable, nothing happens to the boxed copy.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.