Problem with UpdateSourceTrigger=PropertyChanged and StringFormat in WPF

后端 未结 1 1136
萌比男神i
萌比男神i 2021-02-11 05:28

I have a text box in my application which is data bound to a decimal field in my class and the binding mode is two way. I am using StringFormat={0:c} for currency formatting.

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-11 06:13

    The problem is that if you use a converter and update on property changed then WPF will ignore property changes while it is the process of updating the source property. Since the PropertyChanged event is raised from the setter, WPF ignores it.

    The reason it does this is that if you typed "1" in the text box, this would get converted to the decimal value 1.0 and then get converted back to the string "$1.00". This would change the text in the text box and reset the cursor, so if you tried to type "12" you'd end up with "2$1.00".

    Note that your Employee object is getting updated, and the problem is just that the TextBox isn't getting a newly formatted value.

    If you really do want that behavior, you can set IsAsync=True on the binding and WPF will no longer see it as a reentrant change and will allow it. This has also changed in .NET 4.0, so if you upgrade to the latest version of the framework then you should see the behavior you expect.

    0 讨论(0)
提交回复
热议问题