Overwriting the Paste command in Avalon.TextEditor

Veröffentlicht von

How to overwrite preexisting commands in AvalonEdit.

In a project I needed to replace the component for displaying XML code, as the old component became slow with larger files. So I decided to use AvalonEdit as a replacement.

Everthing worked out, except the pasting of texts. Well it works out of the box, but the old component had an event, in which you could modify the content before the paste. The TextEditor, Document of AvalonEdit however did not have such an event.

I was also not successful to just add a new input binding for CTRL + V, as the original command was still. So my solution was to remove the Command from the CommandBinding list and then add a new InputBinding.

var bindings = settingsEditor.TextArea.CommandBindings;
RemovePasteBinding(bindings);
settingsEditor.InputBindings.Add(new InputBinding(new PasteCommand(settingsEditor),
    new KeyGesture(Key.V, System.Windows.Input.ModifierKeys.Control)));

The following code goes through the list of Command bindings and looks for the “Paste” binding. If found it is removed from the list.

private static void RemovePasteBinding(CommandBindingCollection bindings)
{
    CommandBinding pasteCommandBinding = null;

    foreach (CommandBinding commandBinding in bindings)
    {
        if (commandBinding.Command is RoutedUICommand)
        {
            var cmd = (RoutedUICommand)commandBinding.Command;
            if (cmd.Name == "Paste")
            {
                pasteCommandBinding = commandBinding;
            }
        }
    }

    if (pasteCommandBinding != null)
    {
        bindings.Remove(pasteCommandBinding);
    }
}

After that I could assign my own InputBinding for the PasteCommand, which I implemented. By this the paste command can now be captured:

public class PasteCommand : ICommand
{
    private readonly TextEditor _editor;

    public PasteCommand(TextEditor editor)
    {
        _editor = editor;
    }

    public bool CanExecute(object parameter)
    {
        var s = Clipboard.GetText();
        return !string.IsNullOrEmpty(s);
    }

    public void Execute(object parameter)
    {
        var s = Clipboard.GetText();
        
        //do something here

        _editor.Paste(); //paste directly or change the text, for example insert at selection

    }

    public event EventHandler CanExecuteChanged;
}

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert