Bob Tway
Bob Tway

Reputation: 9603

Catching notifications from INotifyPropertyChanged before WPF windows close

In my current application, I have a WPF window with a large number of text fields for the user to fill in. To try and avoid loss of data, I've implemented a feature to notify users if they have unsaved changes.

The underlaying data object in the ViewModel implements INotifyPropertyChanged. So on each change I can set a boolean property on my BaseViewModel to indicate that something has changed. However, this notification only happens when the user moves off any given textbox and onto another part of the window.

The BaseViewModel also has an overridable SaveChanges method, in which the property is reset to indicate the data has been saved.

We're using MVVM, but in a nod to practicality, we do have one bit of code-behind. In the underlying view there's an assignment of a function to the Closing event. In the function, we check the boolean and give the user a messagebox to warn of unsaved changes.

This all works fine in the majority of situations. However, if someone alters text in a box and then goes straight for the close button on the WPF window, the property changed event gets fired after the window closes.

Is there any way I can catch this event and stop the window closing in this eventuality?

Upvotes: 0

Views: 230

Answers (1)

kennyzx
kennyzx

Reputation: 12993

However, this notification only happens when the user moves off any given textbox and onto another part of the window.

You can control this using the UpdateSourceTrigger property.

<TextBox Text="{Binding Width, UpdateSourceTrigger=PropertyChanged}" Width="50" />

For a TextBox, the default value for this property is LostFocus, please refer to the Remarks section of the link.

Upvotes: 2

Related Questions