在使用WPF双向绑定的setter属性变化值 [英] Change value in setter property when using WPF two-way databinding

查看:129
本文介绍了在使用WPF双向绑定的setter属性变化值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到一个实体对象的文本特性的文本框。 我希望能够在某些情况下重新格式化用户输入的文字 - 例如如果用户输入2/4(一小部分) - 。我想改变这种状况,以1/2

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".

通过文本财产的设置部分,我可以改变实体对象的值,但不会出现在文本框 - 它仍然显示为2/4

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"?

推荐答案

这样做的原因是,在WPF的绑定系统智能化,当您更改文本框中的值它假定PropertyChanged事件会火该属性并忽略它。

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();

但困难的是找到一个好地方,在这个挂钩,显然你的数据对象不能做到这一点,因为它没有引用文本框的实例。你可以做到这一点在保存的文本框通过将其链接到数据对象的PropertyChanged事件处理程序的窗口,但不会觉得很干净。

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.

啊哈!更改绑定IsAsync =真:

Aha! Changing the binding to IsAsync=true:

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

出现改变行为,使其的确实的注意PropertyChanged事件,当它发射的制定者。

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

作为附录(32月以后),这种行为已<一个href="http://karlshifflett.word$p$pss.com/2009/05/27/wpf-4-0-data-binding-change-great-feature/">changed在.NET 4 ,你会不会需要IsAsync了。

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

这篇关于在使用WPF双向绑定的setter属性变化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆