Overview
A screen that edits a list should ask “Discard unsaved changes and close?” when the user tries to close the window without saving.
A common way to do this is to put an IsDirty property on the view model and set it to true whenever something changes.
That approach hides two kinds of mistakes.
The first is that IsDirty ends up meaning “a change notification arrived” rather than “the data differs from what was saved”.
This is why it becomes true after merely loading, stays true after a value is changed back, and does not become true after editing a row that was added and then saved.
The second is that when the window is closed with the × button or Alt+F4, the user’s input has not yet reached the view model.
Input that has not arrived is not reflected in IsDirty, so if nothing else has changed, the window closes without asking and the input is lost.
This article measures both problems, then implements, in MVVM, an IsDirty that compares against the values at the time of the last save and a step that commits pending input before the closing check.
Prerequisites and Environment
- Framework: WPF on .NET 8 or later is assumed (.NET 8 and 9 reached end of support by November 2026, so use .NET 10 or later for new projects; .NET support policy). The behavior was measured only in the environment below; .NET 8, .NET 9, and .NET Framework 4.8 were not measured
- Language: C# 12 or later (the code uses collection expressions
[]; C# 12 is the default language version for .NET 8), with nullable reference types enabled - Architecture: MVVM. The view model base class
ObservableObject(whoseSetPropertyraisesPropertyChangedonly when the value changes) is a minimal hand-written implementation with no external library. The view’s code-behind contains onlyInitializeComponent - Closing check: the
IClosingGuardinterface and theClosingGuardattached property from WPF Window.Closing: Why e.Cancel Has No Effect After await, and How to Close Again Safely. The confirmation dialog is shown throughIDialogService.Confirmfrom WPF MVVM Dialogs: A Minimal IDialogService and the Owner and Result Pitfalls - Verified on: .NET 10 / Windows 11. Measurements were taken with a scene in
tools/screenshot-capturethat runs the same types as the code in this article
Problem
The example is a screen that edits a list of customers in a DataGrid and also lets the user edit the selected row’s name in a TextBox above it.
A commonly seen IsDirty subscribes to the collection’s CollectionChanged and to each row’s PropertyChanged, and sets itself to true when a notification arrives.
public sealed class FlagLedgerViewModel : ObservableObject
{
private bool _isDirty;
public FlagLedgerViewModel()
{
// Raised when a row is added or removed.
Customers.CollectionChanged += (_, _) => IsDirty = true;
}
public ObservableCollection<Customer> Customers { get; } = [];
public bool IsDirty
{
get => _isDirty;
private set => SetProperty(ref _isDirty, value);
}
public void Load(IEnumerable<CustomerState> states)
{
foreach (CustomerState state in states)
{
var customer = new Customer { Name = state.Name, Email = state.Email };
// Raised when a loaded row changes.
customer.PropertyChanged += (_, _) => IsDirty = true;
Customers.Add(customer);
}
}
public void Save() => IsDirty = false;
}
Customer is an ObservableObject with Name and Email, defined in the complete implementation.
CustomerState is a pair of values (a record) used for loading and saving, defined in the first obstacle.
This IsDirty becomes true before the user has done anything, yet can stay false after the user edits a row that was added and then saved.
On top of that, with no other changes pending, editing a name cell and pressing × while the cell is still in edit mode leaves IsDirty false, so the window closes without a prompt and the input is lost.
The figure below shows the screen just before × is pressed.
Two mistakes overlap in this symptom: what IsDirty means, and when input reaches the view model.
The sections below deal with them in order.
First Obstacle: A Flag Records That a Notification Arrived, Not That the Data Differs From the Save
The FlagLedgerViewModel above, a variant that adds IsDirty = false; at the end of Load, and a variant that compares against the values at the time of the last save (shown later) were each loaded with three rows, given the same operation, and then had IsDirty read.
| operation | flag | flag, reset to false after loading | compare with saved values |
|---|---|---|---|
| load only | True | False | False |
| change a name | True | True | True |
| change a name, then change it back | True | True | False |
| add a row | True | True | True |
| remove a row | True | True | True |
| move the first row to the end | True | True | True |
| save, then change a loaded row | True | True | True |
| add a row and save, then change the added row | False | False | True |
Each row is the result of applying only that operation to a fresh view model that has just loaded three rows. The third column was measured with the CustomerLedgerViewModel from the complete implementation (its IsDirty is the same as the code below). Measured on .NET 10 / Windows 11.
The flag approach has three faults.
- Loading raises it. In the “load only” row, the flag was
True. Rows are loaded withCustomers.Addafter the subscription, so loading itself raisesCollectionChanged. Resetting the flag tofalseat the end of loading fixes this row (second column) - Changing a value back does not lower it. In the “change a name, then change it back” row, both flag variants stayed
True. The flag only counts change notifications; it never checks whether the values match the last save - Edits to added rows are missed. In the last row, both flag variants were
False. Only the rows loaded inLoadare subscribed toPropertyChanged; a row added later withAddis not. The addition itself raises the flag throughCollectionChanged, but once saving lowers it, nothing watches the added row
Closing the third gap with subscriptions means subscribing to added rows inside CollectionChanged, unsubscribing removed rows, and handling Reset replacements and nested objects inside a row, so the number of paths keeps growing.
Instead of tracking paths, keep a copy of the values at the time of the last save and compare it with the current values on every check.
The third column of the table is that implementation: every operation in the table was judged by its difference from the save, changing a value back gave False, and editing an added row gave True.
public sealed record CustomerState(string Name, string Email);
public sealed class CustomerLedgerViewModel : ObservableObject
{
private IReadOnlyList<CustomerState> _saved = [];
public ObservableCollection<Customer> Customers { get; } = [];
// Compare the current values with the values at the last save.
public bool IsDirty => !TakeSnapshot().SequenceEqual(_saved);
public void Load(IEnumerable<CustomerState> states)
{
Customers.Clear();
foreach (CustomerState state in states)
{
Customers.Add(new Customer { Name = state.Name, Email = state.Email });
}
_saved = TakeSnapshot();
}
public void Save()
{
// Write to a file or other storage here.
_saved = TakeSnapshot();
}
private List<CustomerState> TakeSnapshot() =>
Customers.Select(c => new CustomerState(c.Name, c.Email)).ToList();
}
Because CustomerState is a record, SequenceEqual compares each row’s Name and Email by value.
The current values are captured at the end of both loading and saving, so “load only” gives False.
SequenceEqual also compares order, so, as the “move the first row to the end” row (Customers.Move(0, 2)) shows, reordering rows within the collection also counts as a change.
This code is an excerpt of the CustomerLedgerViewModel in the complete implementation; putting both in one project duplicates the types.
Only values included in CustomerState are compared.
A record’s equality compares each member with that member type’s Equals and does not descend into nested objects (value equality of records; per the reference, not measured in this article).
A List<T> or array in CustomerState is compared by reference, so make nested values records or split them into strings and numbers.
Second Obstacle: With × and Alt+F4, the Input Has Not Reached the View Model
Even with the IsDirty from the first obstacle used in the closing check, pressing × in the state shown in the problem figure produces no prompt.
The default UpdateSourceTrigger of a TextBox.Text binding is LostFocus, so the input is sent to the source when focus leaves the box (UpdateSourceTrigger reference, Controlling When TextBox Input Reaches the Source with UpdateSourceTrigger in WPF).
With the default binding, a DataGrid cell in edit mode also does not update its source until the cell and row edits are committed (Why a WPF DataGrid Edit Does Not Reach the ViewModel When Save Is Clicked, and How to Use CommitEdit).
The window from this article was closed with input still pending, and the values were read at the moment ClosingGuard asked the view model to decide.
The × button was reproduced by sending the same WM_SYSCOMMAND (SC_CLOSE) that the window receives when the button is pressed (WM_SYSCOMMAND reference).
Closing while the window is inactive was reproduced by activating another window of the same app and then sending the same message.
The confirmation dialog was a fake that counts calls and answers “do not discard” (false).
| where the input was typed | closed by | PendingEdits.Commit before the check | Name in the view model at the check | IsDirty at the check | keyboard focus when Closing was raised | confirmations | window |
|---|---|---|---|---|---|---|---|
| nothing typed | SC_CLOSE (same as ×) | no | "Sato" | False | detail TextBox | 0 | closed |
| detail TextBox (default binding), typed "Satox" | SC_CLOSE (same as ×) | no | "Sato" | False | detail TextBox | 0 | closed |
| detail TextBox (default binding), typed "Satox" | Alt+F4 (SendInput) | no | "Sato" | False | detail TextBox | 0 | closed |
| detail TextBox (UpdateSourceTrigger=PropertyChanged), typed "Satox" | SC_CLOSE (same as ×) | no | "Satox" | True | detail TextBox | 1 | stayed open |
| DataGrid cell being edited (default binding), typed "tanaka" | SC_CLOSE (same as ×) | no | "Sato" | False | TextBox in the DataGrid cell | 0 | closed |
| DataGrid cell being edited (UpdateSourceTrigger=PropertyChanged on the column), typed "tanaka" | SC_CLOSE (same as ×) | no | "tanaka" | True | TextBox in the DataGrid cell | 1 | stayed open |
| DataGrid cell being edited (default binding), typed "tanaka" | Alt+F4 (SendInput) | no | "Sato" | False | TextBox in the DataGrid cell | 0 | closed |
| nothing typed | SC_CLOSE (same as ×) | yes | "Sato" | False | detail TextBox | 0 | closed |
| detail TextBox (default binding), typed "Satox" | SC_CLOSE (same as ×) | yes | "Satox" | True | detail TextBox | 1 | stayed open |
| detail TextBox (default binding), typed "Satox" | Alt+F4 (SendInput) | yes | "Satox" | True | detail TextBox | 1 | stayed open |
| DataGrid cell being edited (default binding), typed "tanaka" | SC_CLOSE (same as ×) | yes | "tanaka" | True | TextBox in the DataGrid cell | 1 | stayed open |
| DataGrid cell being edited (default binding), typed "tanaka" | Alt+F4 (SendInput) | yes | "tanaka" | True | TextBox in the DataGrid cell | 1 | stayed open |
| detail TextBox (default binding), typed "Satox" | SC_CLOSE while another window of the same app is active | no | "Sato" | False | another window | 0 | closed |
| detail TextBox (default binding), typed "Satox" | SC_CLOSE while another window of the same app is active | yes | "Satox" | True | another window | 1 | stayed open |
| DataGrid cell being edited (default binding), typed "tanaka" | SC_CLOSE while another window of the same app is active | no | "Sato" | False | another window | 0 | closed |
| DataGrid cell being edited (default binding), typed "tanaka" | SC_CLOSE while another window of the same app is active | yes | "tanaka" | True | another window | 1 | stayed open |
| detail TextBox (UpdateSourceTrigger=Explicit), typed "Satox" | SC_CLOSE (same as ×) | yes | "Satox" | True | detail TextBox | 1 | stayed open |
The view model uses the IsDirty that compares with the saved values, and input was typed with the first row (Name = "Sato") selected. The cell was put into edit mode with DataGrid.BeginEdit, and characters were typed through the InputManager (no IME). Only Alt+F4 was pressed through OS input (SendInput). The “other window” was a WPF window of the same app, made Topmost and activated. Values “at the check” were read by a handler called after ClosingGuard’s Closing handler, and the focus “when Closing was raised” by a handler called before it. Measured on .NET 10 / Windows 11.
In the rows where PendingEdits.Commit before the check is “no”, typing "Satox" into the TextBox with the default binding, or "tanaka" into the DataGrid cell, still left the view model’s Name as "Sato" at the check, and IsDirty was False.
No prompt appeared, and the window closed.
As the “keyboard focus when Closing was raised” column shows, with × and Alt+F4, focus was still in the TextBox that received the input when Closing was raised.
With these two ways of closing, neither the LostFocus update nor the DataGrid row commit (the update of the source) happened.
In the rows closed while another window of the same app was active, keyboard focus had moved to the other window, yet neither the detail TextBox input nor the DataGrid cell input had arrived.
Keyboard focus merely leaving the window did not send the input to the source (the relation to logical focus was not measured).
Writing UpdateSourceTrigger=PropertyChanged on a binding updates the source on every keystroke, so the input reached the view model by the check and the prompt appeared.
This held for both the detail TextBox and the DataGrid column binding.
However, the setting must be written on every binding, and every new input field is another place to forget it.
It also does not end the DataGrid row edit (see the caveats of the DataGrid article).
The approach taken here is to commit all input left in the view immediately before the closing check.
For the focused TextBox, call UpdateSource on its binding; for each DataGrid, call CommitEdit(DataGridEditingUnit.Row, true) to commit through the row.
public static class PendingEdits
{
/// <summary>
/// Commits input left in the view to the source (the view model).
/// Returns false if a DataGrid has a row that cannot be committed.
/// </summary>
public static bool Commit(Window window)
{
// × and Alt+F4 do not move focus, so push the LostFocus binding here.
// Look up logical focus, which remains even when the window is inactive.
if (FocusManager.GetFocusedElement(window) is TextBox box)
{
BindingOperations.GetBindingExpression(box, TextBox.TextProperty)?.UpdateSource();
}
// Commit the rows being edited. Keep committing the other DataGrids even if one fails.
bool committed = true;
foreach (DataGrid grid in FindDescendants<DataGrid>(window))
{
committed &= grid.CommitEdit(DataGridEditingUnit.Row, true);
}
return committed;
}
private static IEnumerable<T> FindDescendants<T>(DependencyObject parent) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child is T found)
{
yield return found;
}
foreach (T descendant in FindDescendants<T>(child))
{
yield return descendant;
}
}
}
}
The TextBox is found through the logical focus kept in the window’s focus scope (FocusManager.GetFocusedElement), not through keyboard focus (Keyboard.FocusedElement).
Only one element on the entire desktop has keyboard focus, and it leaves the window when the window becomes inactive, but logical focus remains (Focus overview).
As the “yes” rows for “SC_CLOSE while another window of the same app is active” show, this lookup delivered the detail TextBox input even when the window was closed while inactive (the DataGrid cell is also covered by the CommitEdit that follows).
While a DataGrid cell is being edited, logical focus is on the cell’s editing TextBox, so both its UpdateSource and CommitEdit are called.
Which of the two delivered the value was not isolated, but the DataGrid article measured that CommitEdit(DataGridEditingUnit.Row, true) alone updates the source.
The &= keeps committing the remaining DataGrids even when one cannot be committed.
PendingEdits is a view-side component that touches controls directly, and the view model never calls it.
It is called from ClosingGuard.OnClosing: add the following if statement right after the e.Cancel = true; commented // stop before the first await (the line before bool? dialogResult = …).
e.Cancel = true; // stop before the first await
// Before the check, commit input left in the view. Do not close if it cannot be committed.
if (!PendingEdits.Commit(window))
{
return;
}
The commit is placed inside ClosingGuard instead of a separate Closing handler to guarantee that it finishes before the check.
As the “yes” rows of the table show, input in both the default-binding detail TextBox and the DataGrid cell reached the view model by the check with each of the three measured ways of closing; IsDirty became True and the prompt appeared.
With nothing typed, IsDirty stayed False even with the commit added, and the window closed without a prompt.
Complete Implementation
The view model is the CustomerLedgerViewModel from the first obstacle, now implementing IClosingGuard so that it shows the confirmation dialog only when there are changes.
ObservableObject and Customer are defined here as well.
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
{
return false;
}
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
}
public sealed class Customer : ObservableObject
{
private string _name = "";
private string _email = "";
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
public string Email
{
get => _email;
set => SetProperty(ref _email, value);
}
}
public sealed record CustomerState(string Name, string Email);
public sealed class CustomerLedgerViewModel : ObservableObject, IClosingGuard
{
private readonly IDialogService _dialogService;
private IReadOnlyList<CustomerState> _saved = [];
private Customer? _selectedCustomer;
public CustomerLedgerViewModel(IDialogService dialogService)
{
_dialogService = dialogService;
}
public ObservableCollection<Customer> Customers { get; } = [];
public Customer? SelectedCustomer
{
get => _selectedCustomer;
set => SetProperty(ref _selectedCustomer, value);
}
// Compare the current values with the values at the last save.
public bool IsDirty => !TakeSnapshot().SequenceEqual(_saved);
public void Load(IEnumerable<CustomerState> states)
{
Customers.Clear();
foreach (CustomerState state in states)
{
Customers.Add(new Customer { Name = state.Name, Email = state.Email });
}
_saved = TakeSnapshot();
SelectedCustomer = Customers.FirstOrDefault();
}
public void Save()
{
// Write to a file or other storage here.
_saved = TakeSnapshot();
}
public Task<bool> CanCloseAsync()
{
bool canClose = !IsDirty
|| _dialogService.Confirm(this, "Discard unsaved changes and close?", "Customers");
return Task.FromResult(canClose);
}
private List<CustomerState> TakeSnapshot() =>
Customers.Select(c => new CustomerState(c.Name, c.Email)).ToList();
}
CanCloseAsync returns true without asking when there are no changes, and otherwise returns the answer from the confirmation dialog.
The confirmation finishes synchronously, so the result is returned with Task.FromResult.
The confirmation dialog in the measurements was a fake that returns false immediately.
Whether the window closes again when OK is chosen in a real IDialogService that shows a MessageBox was not measured.
The view sets ClosingGuard.IsEnabled to True and binds both the detail TextBox and the DataGrid to the same view model.
local is the namespace that contains ClosingGuard.
<Window x:Class="Sample.CustomerLedgerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Sample"
Title="Customers" Width="420" Height="220"
local:ClosingGuard.IsEnabled="True">
<DockPanel Margin="8">
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,8">
<TextBlock Text="Name" Width="50" VerticalAlignment="Center" />
<TextBox x:Name="nameBox" Text="{Binding SelectedCustomer.Name}" />
</DockPanel>
<DataGrid x:Name="grid" ItemsSource="{Binding Customers}"
SelectedItem="{Binding SelectedCustomer}"
AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*" />
<DataGridTextColumn Header="Email" Binding="{Binding Email}" Width="2*" />
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Window>
The measurements loaded the same XAML without x:Class and the namespace declarations through XamlReader, and set the DataContext to a CustomerLedgerViewModel.
In an application, App.OnStartup creates the view model, calls Load, sets it as the window’s DataContext, and then calls Show.
The code-behind needs only InitializeComponent.
Caveats
- The comparison copies every row on each call. Each read of
IsDirtybuilds aCustomerStatefor every row, so the cost grows with the row count. Reading it only for the closing check or when a Save button is pressed means few calls, but the cost of reading it on every keystroke (for example, to show*in the title) was not measured IsDirtydoes not raise change notifications. It is a computed property, soPropertyChangedis never raised for it. To bind it to a title or to a Save button’s enabled state, raise theIsDirtychange from each row’sPropertyChangedand from the collection’sCollectionChanged, and also whenLoadandSaveretake the saved values (LoadraisesCollectionChangedbefore the saved values are retaken, andSavechanges neither the rows nor the collection, so row and collection notifications alone leave the display stale after a load or a save; this follows from the code and was not measured in this article). Forgetting to subscribe to added rows then misses a notification, but the comparison itself still checks against the saved values, so the result of the closing check does not change- Only the
BindingonTextof theTextBoxwith logical focus and theDataGridrows are committed. ATextBoxwith aMultiBindingis not committed (GetBindingExpressionreturns only aBindingExpression, andnullfor aMultiBinding; BindingOperations.GetBindingExpression; per the reference, not measured in this article). Closing with input left in other fields, such as the text of anIsEditableComboBoxor the text field of aDatePicker, was not measured. A binding withUpdateSourceTrigger=Explicitwas sent to the source, becauseUpdateSourceis called (the last row of the table). For a field that usesExplicitto decide when to send, the input stays written to the view model even when the close is cancelled at the prompt (the last row of the table, where the prompt answered “do not discard”). Screens with more than oneDataGridwere not measured - Input that never reaches the source is not detected.
IsDirtycompares view model values, so input thatCommitsends but that cannot be written to the source does not count as a change. In the measurement scene, in a window without aDataGrid,abcwas typed into aTextBoxbound with the default binding to anintproperty, and onlyCommitwas called, without closing: the source kept its value andCommitreturnedtrue(the return value depends only on theDataGrid’sCommitEditresults). Although the binding has neitherValidatesOnExceptionsnor aValidationRule,Validation.GetHasErrorwasFalsebeforeCommitandTrueright after it returned. If the window is closed in this state and there are no other changes,IsDirtystaysFalse, so the window closes without a prompt and the input is lost (this follows from the code and was not measured in this article). Stopping it needs a separate check on the view side for input that did not reach the source (for example, by checkingValidation.GetHasError). Which failures become validation errors depends on the binding and converter settings, so that check is out of scope for this article - By default, a
TextBoxinside aToolBaris not committed.ToolBaris a focus scope by default (FocusManager class), so aTextBoxinside it is not returned as the window’s logical focus (unless it is made the window’s logical focus with FocusManager.SetFocusedElement, in which caseCommitdoes commit it). With a binding that sends at the defaultLostFocustiming, input left in it when the window closes does not reach the view model by the time of the closing check and is not reflected inIsDirty. This follows from the code and the reference and was not measured in this article - The ways of closing measured are three: × (
SC_CLOSE), Alt+F4, andSC_CLOSEwhile another window of the same app is active. Closing through aClosecommand assigned to aMenuorToolBar(the path whereClosingGuard’sCommandBindingcallsClose), closing while another app is active, and closing from the taskbar were not measured - When a row cannot be committed,
Commitreturnsfalseand the close is stopped.CommitEditreturnsfalsefor a row with input that cannot be converted to the property type (measured in the third obstacle of the DataGrid article). The columns in this article are all strings, so this case was not measured on this screen. Whether to show a message explaining why the window did not close depends on the screen - Closes that do not raise
Closing, or that ignore its cancellation, are not covered. The Window.Closing article measured that closing theOwnerwindow does not raiseClosingon the owned window, and that the check has no effect underApplication.Shutdown(including the shutdown that closes the remaining windows whenShutdownModeisOnMainWindowClose). The reference states thatClosingis not raised when the user logs off or shuts down Windows (Window.Closing event; not measured in this article)
Summary
The confirmation fails to appear for two reasons: IsDirty means “a change notification arrived” rather than “the data differs from the last save”, and when the window is closed with × or Alt+F4, the input has not yet reached the view model.
The flag approach was raised by loading, stayed raised after a value was changed back, and missed edits to a row that was added and saved.
Both the default-binding TextBox and the DataGrid cell in edit mode still held the original value at the check with every way of closing that was measured.
Compute IsDirty by keeping the values at load and save time as a list of records and comparing them with the current values on each check.
For the closing check, call PendingEdits.Commit inside ClosingGuard immediately before the check to commit the TextBox with logical focus and the DataGrid rows.
With both in place, input left in the detail TextBox or a DataGrid cell produced a prompt exactly when there were changes, whether the window was closed with ×, Alt+F4, or SC_CLOSE while another window of the same app was active.
Related Articles
- WPF Window.Closing: Why e.Cancel Has No Effect After await, and How to Close Again Safely
- WPF MVVM Dialogs: A Minimal IDialogService and the Owner and Result Pitfalls
- Why a WPF DataGrid Edit Does Not Reach the ViewModel When Save Is Clicked, and How to Use CommitEdit
- Controlling When TextBox Input Reaches the Source with UpdateSourceTrigger in WPF
- WPF SelectedItem Master-Detail: Canceling Edits with a Copy or IEditableObject