Search code examples
c#.netwpfonpaste

How to simulate Paste in a WPF TextBox?


I have a TextBox in my WPF application which I've added a Paste event to using:

DataObject.AddPastingHandler(elm, new DataObjectPastingEventHandler(OnPaste));

Now I want to trigger the OnPaste event from C# code. How can I do this? I tried calling the Paste() function on the control. The text is pasted in the control, but the OnPaste event is not triggered..:

private static void Foo(TextBox textBox, string pastedText)
{
    Clipboard.SetData(DataFormats.Text, pastedText);
    textBox.Paste();
}

Solution

  • Invoke the ApplicationCommand Paste:

    ApplicationCommands.Paste.Execute(this, pastedText)
    

    Please note that this will not work in partial trust!