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?
If your property is a custom dependency property, or if you're working with a derived class where you've defined the instantiation code, the WPF property system has a better way to track property changes. That way is to use the built-in CoerceValueCallback and PropertyChangedCallback property system callbacks.
You enter the first tb 2. You don't enter anything and you click the second one 3. The lostfocus event of tb1 fires and it opens a dialog, and focuses on tb1 again 4. because tb1 got focus, tb2's lostfocus event fires and it does the same, returning focus to tb2 and going on in an infinite loop.
Windows Presentation Foundation (WPF) defines several events that are raised in response to a change in the value of a property. Often the property is a dependency property.
Because this event uses bubbling routing, the element that loses focus might be a child element instead of the element where the event handler is actually attached. Check the Source in the event data to determine the actual element that gained focus.
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}" />
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With