WPF IsDirty: Detect Unsaved Changes Before Closing a Window

A change-flag IsDirty rises on load, stays set after a revert, and misses edits to saved added rows; × and Alt+F4 skip pending input. Commit it, then compare.

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


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.

The Customers window. The Name cell in the first DataGrid row is in edit mode with tanaka typed in it, while the Name TextBox above still shows Sato
The Name cell of the first DataGrid row in edit mode with tanaka typed. The TextBox above, bound to the same row, still shows Sato because the input has not reached the view model. The screen uses the XAML from the complete implementation and the CustomerLedgerViewModel that compares with the saved values. Captured on .NET 10 / Windows 11.

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.

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


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.