Paste Event in a WPF TextBox

code-zoop picture code-zoop · Jun 17, 2010 · Viewed 42.2k times · Source

I have created a custom control inheriting TextBox. This custom control is a numeric TextBox, only supporting numbers.

I am using OnPreviewTextInput to check each new character being typed to see if the character is a valid input. This works great. However, if I paste the text into the TextBox, OnPreviewTextInput is not fired.

What is the best way to capture pasted text in a TextBox?

Also, I have a problem when the back space is pressed, I can't figure out what event this will fire. OnPreviewTextInput is not fired!

Any ideas how to capture pasted text and back space events in WPF TextBox?

Answer

Matt Hamilton picture Matt Hamilton · Jun 17, 2010

Here's some code I had lying around in case I ever needed it. Might help you.

public Window1()
{
    InitializeComponent();

    // "tb" is a TextBox
    DataObject.AddPastingHandler(tb, OnPaste);
}

private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
    var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
    if (!isText) return;

    var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
    ...
}