简体   繁体   中英

How to load a WPF FormattedText object (from RTF or RichTextBox)

My WPF app displays lots of text snippets at various places on a large canvas (a kind of post it note app)

I am currently rendering the text using FormattedText objects and 'drawing them' straight into Visual objects (for speed/efficiency)

Challenge I have is how to load/save/edit that rich text. I'd like to use a RichTextBox to edit the text - but I can't find a way to get the text out of the text box and into a FormattedText object (or visa versa)

Anyone know how this might be achieved? Only way I can think is to have some kind of 'serialise to/from RTF' capability on the FormattedText object - but that doesn't seem to exist.

Thanks

You can iterate through all of the inline objects inside of the RichTextBox.Document, Get all the dependency properties you are interested in, and then set them on a new FormattedText object.

var formattedTextToDraw = new List<FormattedText>();

foreach (var paragraph in RichTextBox.Document.OfType<Paragraph>())
{
    foreach(var inline in paragraph)
    {
        formattedTextToDraw.Add(new FormattedText(
            inline.Text, //Text
            inline.FontSize, //Fontsize
            inline.Foreground, //Color
            etc....) //Other properties for FormattedText constructor
    }
}

The link posted by Clemens above http://www.wpfmentor.com/2009/01/how-to-transfer-rich-text-from.html addresses my issue.

Similar to fooook's answer - iterate through the inline objects and apply their attributes to a FormattedText object.

Shame that FormattedText doesn't support images (like NSAttributedString on iOS/OSX)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM