Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accomplish two-way data binding in WPF?

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?

like image 634
Deniz Dogan Avatar asked Feb 01 '10 21:02

Deniz Dogan


2 Answers

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.

like image 113
itowlson Avatar answered Sep 22 '22 13:09

itowlson


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}
like image 23
Mark Synowiec Avatar answered Sep 22 '22 13:09

Mark Synowiec