David
David

Reputation: 4117

WindowsForms TextBox Method Paste also in WPF TextBox?

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?

Upvotes: 1

Views: 151

Answers (2)

David
David

Reputation: 4117

    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;
    }

Upvotes: 0

michele
michele

Reputation: 2091

Use the Clipboard class:

textBox1.Text = Clipboard.GetText();

or use the SelectedText property of the textbox:

textBox1.SelectedText = "some text";

Upvotes: 1

Related Questions