C# – Paste Event in a WPF TextBox

ceventstextboxwpf

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?

Best Answer

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