Question

I'm using a 'Paste' button command in my view Model to copy RTF from the clipboard. PastedText is my string property that a RichTextBox is bound to in my view:

 private void FormatPastedTextCommandAction()
 {
    PastedText += Clipboard.GetText(TextDataFormat.Rtf);                   
 }

This works and the text is pasted on pressing the Paste button. However, I want to lock down the formatting on the paste function and remove all formatting from the pasted RTF string (colour, italics, set to black Arial 12).

I would just use PastedText += Clipboard.GetText();

to get the plain text but it pastes in at a different font size and I need it in RTF format. I've looked at iterating over the RTF string and doing a find/replace on font size, colour etc. but the RTF is very complex even for a couple of words.

Is there any way around this? Thanks

Was it helpful?

Solution

In the end I used code behind in the view to strip formatting from the RichTextBox itself using a 'Format' button:

 private void _btnFormat_Click(object sender, RoutedEventArgs e)
    {
        TextRange rangeOfText = new TextRange(richTextBoxArticleBody.Document.ContentStart, richTextBoxArticleBody.Document.ContentEnd);
        rangeOfText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
        rangeOfText.ApplyPropertyValue(TextElement.FontSizeProperty, "12");
        rangeOfText.ApplyPropertyValue(TextElement.FontFamilyProperty, "Arial");
        rangeOfText.ApplyPropertyValue(TextElement.FontStyleProperty, "Normal");
        rangeOfText.ApplyPropertyValue(Inline.TextDecorationsProperty, null);
        rangeOfText.ApplyPropertyValue(Paragraph.MarginProperty, new Thickness(0));

    }

This does a good job and doesn't really break the MVVM pattern as the code is UI logic only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top