How to accomplish two-way data binding in WPF?
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}
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.