How to prevent formatting of some types of formatting in WPF RichTextBox

I want to allow some simple formatting commands in WPF RichTextBox, but not others.

I created a toolbar that allows users to use bold or italics and use bulleted or numbered lists. (Basically, I just want to support formatting commands that are suitable for a blog or wiki.)

The problem is that users can perform cut and paste operations that paste text with foreground and background colors, among other types of forbidden formatting. This can lead to unpleasant usability problems, for example, for users pasting white text on a white background.

Is there a way to disable these advanced formatting features? If not, is there a way to intercept the paste operation and format the formatting that I don't want?

+5
source share
2 answers

You can intercept the insert operation as follows:

    void AddPasteHandler()
    {
        DataObject.AddPastingHandler(richTextBox, new DataObjectPastingEventHandler(OnPaste));
    }

    void OnPaste(object sender, DataObjectPastingEventArgs e)
    {
        if (!e.SourceDataObject.GetDataPresent(DataFormats.Rtf, true)) return;
        var rtf = e.SourceDataObject.GetData(DataFormats.Rtf) as string;
        // Change e.SourceDataObject to strip non-basic formatting...
    }

and the dirty part retains some, but not all, of the formatting. The variable rtfwill be a string in RTF format in which you can use a third-party library to parse, walk the tree using a DOM-like pattern and emit a new RTF with only text, bold and italics. Then paste this back into one e.SourceDataObjector several other parameters (see documents below).

Here are the PastingHandlerdocs:

RTF:

+5

, ( , , -):

    void OnPaste(object sender, DataObjectPastingEventArgs e)
    {
        if (!e.SourceDataObject.GetDataPresent(DataFormats.Rtf, true)) return;
        var rtf = e.SourceDataObject.GetData(DataFormats.Rtf) as string;

        FlowDocument document = new FlowDocument();
        document.SetValue(FlowDocument.TextAlignmentProperty, TextAlignment.Left);

        TextRange content = new TextRange(document.ContentStart, document.ContentEnd);

        if (content.CanLoad(DataFormats.Rtf) && string.IsNullOrEmpty(rtf) == false)
        {
            // If so then load it with RTF
            byte[] valueArray = Encoding.ASCII.GetBytes(rtf);
            using (MemoryStream stream = new MemoryStream(valueArray))
            {
                content.Load(stream, DataFormats.Rtf);
            }
        }

        DataObject d = new DataObject();
        d.SetData(DataFormats.Text, content.Text.Replace(Environment.NewLine, "\n"));
        e.DataObject = d;
    }
}
+2

All Articles