1

In WindowsForms i use this samlpe code:

textBox.Paste("some text");

Is there a TextBox method with the same function in WPF? Or there is a nice workaround?

1

2 Answers 2

1

Use the Clipboard class:

textBox1.Text = Clipboard.GetText();

or use the SelectedText property of the textbox:

textBox1.SelectedText = "some text";
2
  • Probably this is not the same, since Paste does replace the currently selected text, whereas your solution will replace all text.
    – Uwe Keim
    Sep 17, 2012 at 11:04
  • Additionally, you use the clipboard whereas the original poster does not use the clipboard.
    – Uwe Keim
    Sep 17, 2012 at 11:05
0
    public static void Paste(this TextBox textbox, string textToInsert)
    {
        int caretIndex = textbox.CaretIndex;
        string textBoxContent;

        if (textbox.SelectedText.Length > 0)
        {
            textBoxContent = textbox.Text.Remove(caretIndex, textbox.SelectedText.Length);
        }
        else
        {
            textBoxContent = textbox.Text;
        }

        textbox.Text = textBoxContent.Insert(caretIndex, textToInsert);
        textbox.CaretIndex = caretIndex + textToInsert.Length;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.