How to accomplish two-way data binding in WPF?

匆匆过客 提交于 2020-05-22 17:03:44

问题


I have heard a lot about two-way bindings in WPF, but I'm not entirely clear on how to accomplish it or what it actually means.

I have a ListView with a bunch of items in it. When the user selects a new item, a TextBox in the application will change its text to display some property of the selected item.

But when the user changes the text in the text box I want the ListView item to be updated immediately as well. Is there any "two-way binding" magical WPF way of accomplishing this?


回答1:


If you haven't you'll need to implement INotifyPropertyChanged for your class that you're binding to.

Also, when you say you want the ListBox item to be updated immediately, you mean that you want it to change as you type in the TextBox. By default the TextBox.Text property updates its source when it loses focus, but you can change this by setting the binding UpdateSourceTrigger to PropertyChanged:

{Binding Source={...}, Path=Whatever, UpdateSourceTrigger=PropertyChanged}



回答2:


Mark's answer shows how to accomplish what you want, but you also asked more generally about "how to accomplish [two-way binding] and what it actually means."

One-way binding means that the binding target (e.g. control) will display data from the binding source (e.g. business object), and will update itself as the business object changes, but that changes to the control will not be propagated back to the business object. E.g. if the Person.Name changes from "bob" to "kate", the TextBlock.Text bound to the Name will change from "bob" to "kate" too.

Two-way binding simply means that not only are changes in the business object reflected in the UI, but changes made by the user in the UI are propagated back to the business object too. So now when the user edits the TextBox.Text bound to the Name, say changing "kate" to "edmund", WPF will set the Person.Name property to "edmund" as well.

To accomplish this, just set Mode=TwoWay on the Binding declaration. Some properties bind two-way by default: TextBox.Text, for example, binds TwoWay by default, which is why Mark's code doesn't need the Mode declaration. In addition, as Mark notes, by default WPF only propagates changes back to the business object when the control loses focus. If you have two UI elements bound to the same property, this can mean they appear out of sync, in which case you can use the UpdateSourceTrigger to force WPF to propagate whenever the property changes.

MSDN covers this in detail with some good clear diagrams: see Data Binding Overview in the WPF SDK.




回答3:


What is the Type of the items in the ListView? To get the two way binding going the need you implement INotifyPropertyChanged...

This might help WPF event property changed?



来源:https://stackoverflow.com/questions/2180221/how-to-accomplish-two-way-data-binding-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!