Vaccano
Vaccano

Reputation: 82517

TwoWay binding is not really Two Way?

I have a two way binding on a string dependency property to the Text of a TextBox.

The binding looks like this:

Text="{Binding MyValue, Mode=TwoWay}"

I have some code that fires in OnKeyUp (in an attached property) that sets MyValue. But rather than taking my value and applying it to the Text property, it is going the other way around.

Here are the sequence of events:

  1. The user enters a string of text that looks like this: 0299900650
  2. The user presses enter.
  3. In my on key up I set MyValue to 2999 and move to the focus to the next field.
  4. The setter for MyValue fires and does a NotifiyPropertyChanged with 2999
  5. The LostFocus fires.
  6. The setter for MyValue fires and does a NotifiyPropertyChanged with 0299900650.

It seems to me that my value is not making it back to "TextBox.Text" somehow. When I loose focus the TextBox is updating the value of the string with what it has in the Text property (the unchanged value because my change did not get back.)

Is there some WPF magic I am not aware of here?

NOTE: I have double checked my bindings. (Besides they work from the UI so I imagine they are correct going to the UI.)

NOTE II: When I say the "user enters a string", it is really a scanned barcode. But since I am using a keyboard wedge, it is as if it was typed in. (However, the whole point of setting the value is because I am doing something different if the user scans as apposed to typing.)

UPDATE: I found this was due to another property having a side effect. I was able to fix the problem.

Upvotes: 0

Views: 157

Answers (2)

Vaccano
Vaccano

Reputation: 82517

I found this was due to another property having a side effect. I was able to fix the problem by fixing that side effect.

Upvotes: 0

Tigran
Tigran

Reputation: 62265

You simply jump into the concurency conflict on WPF binding messaging. To prove that, do the following:

  • remove your OnKeyUp even handler

and do the same you did. On Enter click binding mechanism fires and sets your code behind property.

In case when you make on KeyUp, you new value 2999 is surpressed by the binding after.

To manage this correctly make use of Converter and get rid of OnKeyDown even subscription.

Upvotes: 2

Related Questions