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


  • Visual Studio 'Tea & Technology' Video Miniseries Starts Next Week

    The goal of the miniseries is to provide an insider's snapshot look at some of the people who contribute to shaping the Visual Studio IDE every day.

  • Microsoft Releases OpenJDK 21 Build for Java Jockeys

    Microsoft today announced its "Microsoft Build of OpenJDK 21," taking advantage of new features and functionality in Java 21.

  • 'Dev Home' Update Leads Developer Goodies in AI-Powered Windows 11 Update

    Along with today's new AI-powered Windows 11 update come new goodies for developers, including a new edition of Dev Home, a preview offering described as a "control center" providing coding-focused features and functionality.

  • Community Dev Gives VS Code Python Some YAPF

    The latest update to Python in Visual Studio Code includes a new extension for Python formatting that was contributed by a member of the open source community.

Subscribe on YouTube