How to force WPF property binding to update its source value?

csharp

(Yassine) #1

My TextBox.Text property is Attached to a none updating property (within a none INotifyPropertyChanged class), so want to inform that property that it’s value should be updated, in other words I want to update the source value!

how can i get that done?


(SAM) #2

You can implement this little method:

private void UpdateMyPropertyValue()
{
    YourTextBoxHere.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
}

And by the way, you are confusing source and target values in your question, here the functionality you want is to update the TargetValue which is the property where your TextBox.TextProperty is bound to.

hope that fixes your issue.


(jms) #3

Let me take a little of your time to clear this out, So in this case we are talking about Updating the Source not the Target right!

So mainly there are two methods we can use:

  1. BindingExpression.UpdateSource():
    UpdateSource() Method updates the source property of a given binding with the current value in the target Control Property.

Remarks:
This method does nothing when the Mode of the binding is not TwoWay or OneWayToSource.

Read more…

  1. BindingExpression.UpdateTarget():
    UpdateTarget() Method forces the target Control to updates it’s property value, from the source property.

This method is useful if your source property model doesn’t implement INotifyPropertyChanged or any other property changed notification mechanism.

Read more…


Examples:

  • To update TextBox.TextProperty by re-pulling a fresh value from the source model:
    YourTextBox.GetBindingExpression(TextBox.TextProperty).UpdateTarget();

  • To send the latest TextBox.TextProperty value (in the UI) to the source model property:
    YourTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();

Finally; So UpdateTarget() is to update the User interface (The Control) while Up dateSource() updates the bound model property.

Hope this helps explaining the difference, and how both can be used.


(Yassine) #4

Thanks a lot :blush: that really helped, and explains the confusion.
But somehow it didn’t work for my TextBox.TextProperty MultiBinding, so i had to use this code below:

BindingOperations.GetBindingExpressionBase(tb_username_TextBox, TextBox.TextProperty).UpdateSource();