views:

148

answers:

3

Suppose I want to databinding two TextBox. I can do it in XAML:

<TextBox x:Name="FirstBox" Text="{Binding Text, Mode=TwoWay, ElementName= SecondBox}"></TextBox>
<TextBox x:Name="SecondBox"></TextBox>

Or, I can do it programmatically.

    Binding binding = new Binding("Text");
    binding.Mode = BindingMode.TwoWay;
    binding.Source = SecondBox;
    FirstBox.SetBinding(TextBox.TextProperty, binding);

The problem is, when I type something in SecondBox, it immediately reflects in FirstBox. However, typing in FirstBox doesn't show in SecondBox immediately. SecondBox is updated only when focus out FirstBox.

Surely, I can build another Binding for SecondBox. But, is there any other way to make change in FirstBox immediately update SecondBox?

+2  A: 

There are probably other ways that include chunks of code but I can't think of an easier way if that is what you are really asking. Why would you not use another binding on the SecondBox to watch the first (I'm assuming this is some simplification of a scenario where doing any of this actually makes sense)?

AnthonyWJones
A: 

I think this is expected behavior for a TextBox. From http://msdn.microsoft.com/en-us/library/cc278072%28VS.95%29.aspx

Updating the Data Source In TwoWay bindings, changes to the target automatically update the source, except when binding to the Text property of a TextBox. In this case, the update occurs when the TextBox loses focus.

I think you need to also bind the Text property on the second TextBox to get the behavior you want as Anthony suggested.

James Cadd
+1  A: 

You can achieve this with a little bit of code. The Xaml looks like this:

<TextBox x:Name="tb1" Text="{Binding Path=Text, ElementName=tb2, Mode=TwoWay, UpdateSourceTrigger=Explicit}" TextChanged="tb1_TextChanged" />
<TextBox x:Name="tb2" />

This is the same as what you have, except that we are setting "UpdateSourceTrigger=Explicit" and we are registering for the TextChanged event. By default, bindings on TextBox.Text get updated when the TextBox loses focus. By setting "UpdateSourceTrigger=Explicit" we are overriding the default update behavior and we need to explicitly say when to update the bindings. So we have the TextChanged event handler that looks like this:

private void tb1_TextChanged(object sender, TextChangedEventArgs e)
{
    tb1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
KeithMahoney