Paste as Plain Text in Windows Store App

I was working on a Windows Store app that used a RichEditBox for text entry. Everything worked great until I pasted some formatted text into it. The dumb thing kept all the formatting! Okay, I guess that’s probably good since it would be pretty annoying if you wanted the formatting, but I didn’t.

Good news, though: it’s easy to remove that formatting and paste as plain text. So easy, in fact, that you can do it in a single line. RichEditBox has an ITextDocument property (Document) that has an ITextRange property (Selection). And guess what ITextRange has? A Paste method! However, this is where it got a little tricky for me because Paste takes an integer parameter, and it took me some googling to find a list of valid values. (Sorry, text-pasting enthusiasts, but you can’t use DataFormats in a Windows Store app.) In the end, I was able to find what I needed here.

Once you’ve got the code, you just hook up a handler to the RichEditBox’s Paste event and–voila!–pasting as plain text.

XAML:

<RichEditBox Paste="OnPaste" />

Code-behind:

private void OnPaste(object sender, TextControlPasteEventArgs e)
{
    var editBox = sender as RichEditBox;
    if (editBox.Document.CanPaste())
    {
        editBox.Document.Selection.Paste(1);
        e.Handled = true;
    }
}
Advertisements

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s