Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

.net - 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”?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...