WPF RaisePropertyChanged event on lost focus

2019-02-13 15:31发布

问题:

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:

  1. Edit the text box
  2. Click on another control
  3. RaisePropertyChanged is fired, the viewmodel is updated
  4. Click on save button on the menu
  5. Data Saved with correct values

This sequence gives me an error:

  1. Edit the text box
  2. Click on save button on the menu
  3. Data Saved with correct values

How to solve this?

回答1:

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}" />


回答2:

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.)



标签: c# wpf mvvm