Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value in setter property when using WPF two-way databinding

I have a TextBox that is bound to a Text-property on an Entity-object. I'd like to be able to re-format the text the user enters in some circumstances - e.g. if the user enters "2/4" (a fraction) - I'd like to change that to "1/2".

Via the “set-part” of the Text-property, I can change the value on the Entity-object, but that doesn't appear in the TextBox – it still reads “2/4”?

like image 494
Kenneth Kryger Sørensen Avatar asked May 13 '09 10:05

Kenneth Kryger Sørensen


1 Answers

The reason for this is that the binding system in WPF is "intelligent" and when you change the value in the TextBox it assumes that the PropertyChanged event will fire for that property and ignores it.

You can force the TextBox to refresh its bindings by calling:

textBox.GetBindingExpression(TextBox.TextProperty).UpdateTarget();

but the difficulty is finding a good place to hook this in. Obviously your data object can't do it since it has no reference to the TextBox instance. You could do it in the window that holds the TextBox by linking it to the PropertyChanged event handler of the data object, but that doesn't feel very clean.

I'll edit this response if I think of a better solution, but at least this explains the reason that the binding isn't working.


Aha! Changing the binding to IsAsync=true:

<TextBox x:Name="textBox" Text="{Binding Path=TestData, IsAsync=true}"/>

Appears to alter the behaviour so that it does pay attention to the PropertyChanged event when it's fired by the setter.


As an addendum (32 months later) this behaviour has been changed in .NET 4 and you won't need the IsAsync anymore.

like image 99
Martin Harris Avatar answered Nov 11 '22 02:11

Martin Harris