C# – Binding when a button is pressed (Explicit binding) has always BindingExpression at null

.netbindingc++wpf

I have a textbox that contain a string that must be binded only when the user press the button. In XAML:

<Button Command="{Binding Path=PingCommand}" Click="Button_Click">Go</Button>
<TextBox x:Name="txtUrl" Text="{Binding Path=Url,UpdateSourceTrigger=Explicit, Mode=OneWay}" />

In the code-behind:

private void Button_Click(object sender, RoutedEventArgs e)
{  
    BindingExpression be = this.txtUrl.GetBindingExpression(TextBox.TextProperty);
    be.UpdateTarget();
}

"be" is always NULL. Why?

Update:

Alright, here is some update after a lot of try.

IF, I set the Mode the OneWay with Explicit update. I have a NullReferenceException in the "be" object from the GetBindingExpression.

IF, I set the Mode to nothing (default TwoWay) with Explicit update. I have the binding getting the value (string.empty) and it erases every times everything in the textbox.

IF, I set the Mode to OneWay, with PropertyChanged I have nothing raised by the property binded when I press keys in the textbox and once I click the button, I have a NULLReferenceException in the "be" object.

IF, I set the Mode to nothing (default TwoWay), with PropertyChanged I have the property that raise everytime I press (GOOD) but I do not want to have the property change everytime the user press a key… but only once the user press the Button.

Best Solution

Alright, after thinking a little more I noticed that :

 BindingExpression be = this.txtUrl.GetBindingExpression(TextBox.TextProperty);
 be.UpdateTarget();

Has something illogical because I do not want to update the Target but the source. I have simply changed be.Updatetarget() to be.UpdateSource(); and everything worked with this XAML:

 <TextBox x:Name="txtUrl" Text="{Binding Path=Url, UpdateSourceTrigger=Explicit}">...

Thank you to everybody who have helped me in the process to solve this problem. I have added +1 to everybody! Thanks

Related Question