Just a short question :
In wpf, how do I set and get updatesourcetrigger of a textbox in codebehind ?
Thanks
Update :
I follow AngleWPF's code :
var bndExp = BindingOperations.GetBindingExpression(this, TextBox.TextProperty);
var myBinding
= bndExp.ParentBinding;
var updateSourceTrigger = myBinding.UpdateSourceTrigger;
But I got the exception :
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll Additional information: Exception has been thrown by the target of an invocation.
What do you mean by UpdateSourceTrigger
of TextBox
? You mean to say UpdateSourceTrigger
of TextBox.TextProperty
's Binding
?
E.g. if you have a TextBox
named myTextBox
having its Text
property bound to some source then you can easily get it's UpdateSourceTrigger
and Binding
object via GetBindingExpression()
call.
var bndExp
= BindingOperations.GetBindingExpression(myTextBox, TextBox.Textproperty);
var myBinding
= bndExp.ParentBinding;
var updateSourceTrigger
= myBinding.UpdateSourceTrigger;
But it is tricky to set UpdateSourceTrigger
for an already used binding. E.g. in the above case you wont be able to set the myBinding.UpdateSourceTrigger
to something else. This is not allowed when a binding object is already in use.
You may have to deep clone the binding object and set new UpdateSourceTrigger
to it and assign it back to the TextBox
. Cloning does not exist for Binding
class. You may have to write your own cloning code for the same.
var newBinding = Clone(myBinding); //// <--- You may have to code this function.
newBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
myTextBox.SetBinding(TextBox.TextProperty, newBinding);
Alternately ou can also try to detatch the existing Binding and update it and assign it back...
myTextBox.SetBinding(TextBox.TextProperty, null);
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
myTextBox.SetBinding(TextBox.TextProperty, myBinding);
Let me know if any of these tips helps.