Created
December 29, 2020 00:30
-
-
Save ramtinak/01b874bcc114055b0906b1aceb0bd1b6 to your computer and use it in GitHub Desktop.
A tiny class for adding Undo Redo option to your projects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace RamtinJokar | |
{ | |
public class UndoRedo<T> | |
{ | |
private readonly Stack<T> UndoStack; | |
private readonly Stack<T> RedoStack; | |
public event EventHandler<UndoRedoEventArgs<T>> UndoHappened; | |
public event EventHandler<UndoRedoEventArgs<T>> RedoHappened; | |
public T CurrentItem { get; private set; } | |
public bool CanUndo => UndoStack.Count > 0; | |
public bool CanRedo => RedoStack.Count > 0; | |
public IReadOnlyList<T> UndoItems => UndoStack?.ToList(); | |
public IReadOnlyList<T> RedoItems => RedoStack?.ToList(); | |
public UndoRedo() | |
{ | |
UndoStack = new Stack<T>(); | |
RedoStack = new Stack<T>(); | |
} | |
public void Reset() | |
{ | |
UndoStack.Clear(); | |
RedoStack.Clear(); | |
CurrentItem = default; | |
} | |
public void Add(T item) | |
{ | |
UndoStack.Push(item); | |
CurrentItem = item; | |
RedoStack.Clear(); | |
} | |
public void Undo() | |
{ | |
if (!CanUndo) return; | |
RedoStack.Push(CurrentItem); | |
CurrentItem = UndoStack.Pop(); | |
UndoHappened?.Invoke(this, new UndoRedoEventArgs<T>(CurrentItem)); | |
} | |
public void Redo() | |
{ | |
if (!CanRedo) return; | |
UndoStack.Push(CurrentItem); | |
CurrentItem = RedoStack.Pop(); | |
RedoHappened?.Invoke(this, new UndoRedoEventArgs<T>(CurrentItem)); | |
} | |
} | |
public class UndoRedoEventArgs<T> : EventArgs | |
{ | |
public T CurrentItem { get; } | |
public UndoRedoEventArgs(T currentItem) => CurrentItem = currentItem; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment