The .NET Command Pattern, Part 2: Listing 1

The CommandStateManager class

using System;
using System.Collections.Generic;
using System.ComponentModel;
using VSMCommandPatternUndo.Commands;
 
namespace VSMCommandPatternUndo
{
    public class CommandStateManager : INotifyPropertyChanged
    {
        private static readonly Lazy<CommandStateManager> _instance = new
Lazy<CommandStateManager>(() => new CommandStateManager()); private Stack<IUndoCommand> _undos = new Stack<IUndoCommand>(); private Stack<IUndoCommand> _redos = new Stack<IUndoCommand>(); public static CommandStateManager Instance { get { return _instance.Value; } } public bool CanUndo { get { return _undos.Count > 0; } } public bool CanRedo { get { return _redos.Count > 0; } } private CommandStateManager() { } public void Executed(IUndoCommand command) { _undos.Push(command); OnNotifyPropertyChanged("CanUndo"); } public void Undo() { if (CanUndo) { IUndoCommand command = _undos.Pop(); _redos.Push(command); command.Undo(); OnNotifyPropertyChanged("CanRedo"); } } public void Redo() { if (CanRedo) { IUndoCommand command = _redos.Pop(); _undos.Push(command); command.Execute(null); OnNotifyPropertyChanged("CanUndo"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnNotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Visual Studio Insiders Further Refines Copilot Usage Tracking

    With devs reeling from usage-based billing sticker shock, Visual Studio 18.9 makes monthly Copilot plan usage easier to reach from the coding workflow while adding more cost information to a redesigned model picker.

  • VS Code 1.130 Expands Agent Host and Review Tools

    Microsoft's latest weekly VS Code release advances shared agent sessions, multi-file change review, chat visibility and terminal navigation

  • Microsoft Agent Framework Makeover: Claws, Loops and Harnesses

    Microsoft's newly released Agent Framework Harness packages the loops, planning, memory, context management and safety controls that developers previously had to assemble around AI models themselves.

  • Visual Studio 2026 Gives Copilot Built-In Skills -- and Makes Them Prove Their Worth

    Microsoft is moving Agent Skills beyond bring-your-own instructions by shipping expert-authored workflows with the IDE, while keeping them off by default until testing shows their benefits justify the additional token use.

Subscribe on YouTube