回复 1楼shengairong的帖子
可以通过集成 ActionBase 和实现 IUndo 来自定义 Undo/Redo , 请参考以下代码:
- namespace SetForeColorUndoAction
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- string[,] values = { {"aa", "bb"}, {"cc", "dd"}};
- this.spread1.ActiveSheet.SetArray(0,0, values);
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- SetCellForeColorUndoAction action = new SetCellForeColorUndoAction(this.spread1.ActiveSheet, new CellRange(0, 0, 2, 2), Colors.Red);
- this.spread1.UndoManager.Do(action);
- }
- }
- internal class SetCellForeColorUndoAction : ActionBase, IUndo
- {
- private Worksheet _workSheet = null;
- private CellRange _cellRange = null;
- private Color? _foreColor = null;
- private List<CellData> _cachedForeground = new List<CellData>();
- public SetCellForeColorUndoAction(Worksheet workSheet, CellRange cellRange, Color foreColor)
- {
- _workSheet = workSheet;
- _cellRange = cellRange;
- _foreColor = foreColor;
- }
- public override void Execute(object parameter)
- {
- if (this.CanExecute(parameter))
- {
- SheetView sheetView = parameter as SheetView;
- try
- {
- this.SaveState();
- for (int row = _cellRange.Row; row < _cellRange.Row + _cellRange.RowCount; row++)
- {
- for (int column = _cellRange.Column; column < _cellRange.Column + _cellRange.ColumnCount; column++)
- {
- _workSheet.Cells[row, column].Foreground = new SolidColorBrush(_foreColor.Value);
- }
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
- this.ResumeInvalidate(sheetView);
- }
- }
- }
- public override bool CanExecute(object parameter)
- {
- return true;
- }
- public bool CanUndo
- {
- get
- {
- return true;
- }
- }
- public void SaveState()
- {
- for (int row = _cellRange.Row; row < _cellRange.Row + _cellRange.RowCount; row++)
- {
- for (int column = _cellRange.Column; column < _cellRange.Column + _cellRange.ColumnCount; column++)
- {
- _cachedForeground.Add(new CellData(row, column, _workSheet.Cells[row, column].Foreground));
- }
- }
- }
- public bool Undo(object parameter)
- {
- SheetView sheetView = parameter as SheetView;
- bool result;
- try
- {
- result = this.Undo(sheetView);
- }
- finally
- {
- }
- return result;
- }
- private bool Undo(SheetView sheetView)
- {
- foreach (var item in _cachedForeground)
- {
- _workSheet.Cells[item.Row, item.Column].Foreground = item.Value as Brush;
- }
- return true;
- }
- public override string ToString()
- {
- return "Undo Set ForeColor";
- }
- }
- internal struct CellData
- {
- private int row;
- private int column;
- private object value;
- public CellData(int row, int column, object value)
- {
- this.row = row;
- this.column = column;
- this.value = value;
- }
- public int Row
- {
- get { return row; }
- }
- public int Column
- {
- get { return column; }
- }
- public object Value
- {
- get { return this.value; }
- }
- }
- }
复制代码 |