DotNetElements.UndoRedo
0.1.0
Prefix Reserved
dotnet add package DotNetElements.UndoRedo --version 0.1.0
NuGet\Install-Package DotNetElements.UndoRedo -Version 0.1.0
<PackageReference Include="DotNetElements.UndoRedo" Version="0.1.0" />
<PackageVersion Include="DotNetElements.UndoRedo" Version="0.1.0" />
<PackageReference Include="DotNetElements.UndoRedo" />
paket add DotNetElements.UndoRedo --version 0.1.0
#r "nuget: DotNetElements.UndoRedo, 0.1.0"
#:package DotNetElements.UndoRedo@0.1.0
#addin nuget:?package=DotNetElements.UndoRedo&version=0.1.0
#tool nuget:?package=DotNetElements.UndoRedo&version=0.1.0
DotNetElements.UndoRedo
A lightweight, AOT-friendly, reflection-free Undo/Redo framework for .NET 10, designed to pair seamlessly with CommunityToolkit.Mvvm partial properties and a Roslyn Incremental Source Generator.
Features
- Zero-boilerplate MVVM tracking via Roslyn Source Generation (
[Undoable],[UndoableIgnore]) hooking directly into CommunityToolkit.Mvvm's[ObservableProperty]partial properties. - Automatic object-graph propagation (
IUndoableNode): AttachUndoRedoManageronce at the root ViewModel and it automatically cascades to nested ViewModels andUndoableCollection<T>items (and detaches them when removed). - AvaloniaUI-ready:
UndoRedoManagerinheritsObservableObjectand exposesUndoCommand,RedoCommand,CanUndo,CanRedo,NextUndoDescription,NextRedoDescription, andIsDirty. - Action coalescing (merging): Rapid changes (e.g., slider drags or typing in a
TextBox) merge into a single undo entry using a configurableMergeTimeoutMswindow. - Nested transactions: Group multiple property and collection mutations into one atomic undo step with
BeginTransaction(...). - Suspend recording: Hydrate or load ViewModels without polluting history using
Suspend(). - Dirty-state tracking:
IsDirtyandMarkSaved()accurately track whether the current state matches the last saved checkpoint—even across undo, redo, coalescing, and capacity eviction. - Bounded history: Optional
maxCapacityto cap memory usage. - 100% AOT & trimming friendly: No reflection or runtime proxies.
Solution Layout
| Project | Target | Description |
|---|---|---|
DotNetElements.UndoRedo |
net10.0 |
Core runtime library (UndoRedoManager, UndoableCollection<T>, IUndoableAction, IUndoableNode, attributes). |
DotNetElements.UndoRedo.Generators |
netstandard2.0 |
Roslyn Incremental Source Generator for [Undoable] partial classes and properties. |
DotNetElements.UndoRedo.Sample |
net10.0 |
Runnable console demo showcasing a 3-level ViewModel graph. |
DotNetElements.UndoRedo.Tests |
net10.0 |
xUnit test suite covering runtime features and generated code. |
Installation
Install the package from NuGet. It bundles the Roslyn source generator under analyzers/dotnet/cs/, so no separate analyzer reference is required:
dotnet add package DotNetElements.UndoRedo
From Source
When working inside this repository, reference the runtime library and the source generator projects directly:
<ItemGroup>
<ProjectReference Include="..\..\src\UndoRedo\UndoRedo.csproj" />
<ProjectReference Include="..\..\src\Generators\Generators.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
Quick Start
1. Define Your ViewModels
You can use either Opt-Out mode ([Undoable] on the class) or Opt-In mode ([Undoable] only on specific properties).
Opt-Out Mode (track all [ObservableProperty] members except [UndoableIgnore])
using CommunityToolkit.Mvvm.ComponentModel;
using DotNetElements.UndoRedo;
[Undoable]
public partial class DocumentViewModel : ObservableObject
{
[ObservableProperty]
[Undoable(Description = "Rename Document")]
public partial string Title { get; set; } = string.Empty;
[ObservableProperty]
[Undoable(MergeTimeoutMs = 300)]
public partial double Zoom { get; set; } = 1.0;
[ObservableProperty]
[UndoableIgnore] // Excluded from undo history (UI-only state)
public partial bool IsPreviewMode { get; set; }
public UndoableCollection<LayerViewModel> Layers { get; } = [];
}
[Undoable]
public partial class LayerViewModel : ObservableObject
{
[ObservableProperty]
public partial string Name { get; set; } = string.Empty;
[ObservableProperty]
public partial double Opacity { get; set; } = 1.0;
public UndoableCollection<ShapeViewModel> Shapes { get; } = [];
}
[Undoable]
public partial class ShapeViewModel : ObservableObject
{
[ObservableProperty]
public partial double X { get; set; }
[ObservableProperty]
public partial double Y { get; set; }
}
Opt-In Mode (track only decorated properties—no [UndoableIgnore] needed)
public partial class SettingsViewModel : ObservableObject
{
[ObservableProperty]
[Undoable(MergeTimeoutMs = 400)]
public partial string UserName { get; set; } = string.Empty;
[ObservableProperty] // Automatically ignored
public partial bool IsExpanded { get; set; }
}
2. Attach UndoRedoManager at the Root
Build your initial object graph before attaching so initialization doesn't pollute the undo stack, then call undo.Attach(root) once:
var undo = new UndoRedoManager(maxCapacity: 100);
var document = new DocumentViewModel { Title = "Untitled", Zoom = 1.0 };
var layer = new LayerViewModel { Name = "Background" };
layer.Shapes.Add(new ShapeViewModel { X = 10, Y = 20 });
document.Layers.Add(layer);
// Cascades UndoRedoManager down through Document -> Layers -> Shapes
undo.Attach(document);
// All edits anywhere in the graph are now tracked automatically!
document.Title = "Poster Design";
layer.Shapes[0].X = 150;
undo.Undo(); // Shape.X -> 10
undo.Undo(); // Title -> "Untitled"
undo.Redo(); // Title -> "Poster Design"
AvaloniaUI Integration
UndoRedoManager is an ObservableObject with generated [RelayCommand] properties, so it binds directly in XAML:
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.KeyBindings>
<KeyBinding Gesture="Ctrl+Z" Command="{Binding UndoRedo.UndoCommand}" />
<KeyBinding Gesture="Ctrl+Y" Command="{Binding UndoRedo.RedoCommand}" />
<KeyBinding Gesture="Ctrl+Shift+Z" Command="{Binding UndoRedo.RedoCommand}" />
</Window.KeyBindings>
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Content="Undo"
Command="{Binding UndoRedo.UndoCommand}"
ToolTip.Tip="{Binding UndoRedo.NextUndoDescription}" />
<Button Content="Redo"
Command="{Binding UndoRedo.RedoCommand}"
ToolTip.Tip="{Binding UndoRedo.NextRedoDescription}" />
<TextBlock Text="*"
IsVisible="{Binding UndoRedo.IsDirty}" />
</StackPanel>
</Window>
Core Concepts & API Reference
Automatic Object Graph Propagation (IUndoableNode & UndoableCollection<T>)
Every class processed by the source generator automatically implements IUndoableNode (UndoRedoManager? UndoRedo { get; set; }):
- Setting
UndoRedoon a parent cascades to all childIUndoableNodeproperties andUndoableCollection<T>properties. - Adding a new
IUndoableNodeto anUndoableCollection<T>automatically attaches the collection'sUndoRedoManager. - Removing an item detaches it (
UndoRedo = null) so off-tree mutations don't record phantom history; undoing the removal re-attaches it cleanly. - Replacing a tracked
IUndoableNodeproperty automatically detaches the old value and attaches the new value.
Transactions (BeginTransaction)
Group multiple property and collection mutations into a single atomic undo/redo entry. Transactions can be nested and empty transactions are ignored:
using (undo.BeginTransaction("Reset Canvas"))
{
document.Title = "Blank";
document.Zoom = 1.0;
document.Layers.Clear();
}
// A single undo.Undo() reverts all three changes in reverse order.
Action Coalescing (MergeTimeoutMs)
Specify MergeTimeoutMs on [Undoable] (at class or property level) to merge consecutive edits to the same property within a rolling time window:
[ObservableProperty]
[Undoable(MergeTimeoutMs = 300)]
public partial double Opacity { get; set; } = 1.0;
For deterministic unit testing without Thread.Sleep, pass a custom TimeProvider to new UndoRedoManager(timeProvider: myFakeClock).
Suspending Recording (Suspend)
Temporarily silence history recording (e.g., while loading a file or hydrating state). Supports nesting:
using (undo.Suspend())
{
document.Title = loaded.Title;
document.Zoom = loaded.Zoom;
}
Dirty-State Tracking (IsDirty & MarkSaved)
- Starts as
IsDirty == false. - Becomes
trueafter any recorded change, and automatically returns tofalseif the user undoes back to the saved state. - Call
undo.MarkSaved()after persisting the document to move the clean checkpoint to the current history position.
Custom Actions (IUndoableAction & DelegateUndoableAction)
For operations outside simple property or collection changes, record a DelegateUndoableAction or implement IUndoableAction:
undo.Record(new DelegateUndoableAction(
description: "Rotate Canvas 90°",
undo: () => Rotate(-90),
redo: () => Rotate(90)));
How the Source Generator Works
For each tracked [ObservableProperty] partial property, UndoableGenerator emits implementations of CommunityToolkit.Mvvm's On<Prop>Changing(T value) and On<Prop>Changed(T value) partial methods:
On<Prop>Changingcaptures the current property value before the backingfieldis overwritten.On<Prop>Changedreads and clears the temporary previous value (preventing reference retention), attaches/detachesIUndoableNodevalues when applicable, and callsUndoRedo?.RecordPropertyChange(...).
Because UndoRedoManager.IsRestoring is true during Undo() and Redo(), restoring values via the setter delegate never re-records duplicate entries.
Building & Running Tests
# Build the entire solution
dotnet build DotNetElements.UndoRedo.slnx
# Run all unit tests
dotnet test DotNetElements.UndoRedo.slnx
# Run the console sample
dotnet run --project samples/Sample/Sample.csproj
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- CommunityToolkit.Mvvm (>= 8.4.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.0 | 90 | 11/26/2026 |