Reputation: 3061
I have a C# WPF MVVM application that works fine.
The only problem is when I modify a textbox and click on the menu. If I do that without clicking on another control, the view->viewmodel event is never fired because the textbox hasn't lost focus. Correct me if I am wrong, but I think the RaisePropertyChanged is only fired on LostFocus (or OnBlur, or any similar event).
So, clicking on the menu save button right after editing the textbox causes the viewmodel to save the data using old values.
So, resuming:
This sequence works fine:
This sequence gives me an error:
How to solve this?
Upvotes: 9
Views: 10873
Reputation: 12811
This is a common gotcha with TextBoxes in both WPF and WinForms. You can get around this by instructing the binding system to update the VM with every change to the TextBox instead of when it loses focus. To do this, set the UpdateSourceTrigger
of the binding to PropertyChanged
. This will write back to the VM any time the TextBox raises the PropertyChanged
event for its Text
property.
<TextBox Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Upvotes: 13
Reputation: 102793
For the TextBox.Text
dependency property, its default UpdateSourceTrigger
is LostFocus
(ie, your view model property gets updated when the control loses focus). To make the property update immediately whenever text is entered, set UpdateSourceTrigger=PropertyChanged
. (See the link above for more info -- it actually covers your example specifically.)
Upvotes: 8