简体   繁体   中英

Save RichTextBox content containing both images and custom token elements

Struggling with how to successfully save and load my System.Windows.Controls.RichTextBox content containing all of the following: formatted text, images, custom type-defined token elements, custom dynamic token elements.

By token elements I mean my custom classes inheriting from System.Windows.Documents.Run where type-defined is such that does not need to remember any dynamically set property values (since action is taken based on the type which needs to be remembered after loading) and dynamic ones are such that need to also retain dynamically set properties (action is taken not only based on type, but also based on these set values).

I know of the following 3 methods to save/load, neither of which is sufficient:

1)

string xamlStream = System.Windows.Markup.XamlWriter.Save(myRichTxtBx.Document);

and then saving the string

2)

TextRange content = new TextRange(myRichTxtBx.Document.ContentStart, myRichTxtBx.Document.ContentEnd);
content.Save(myFileStream, DataFormats.XamlPackage, true);

3)

TextRange content = new TextRange(myRichTxtBx.Document.ContentStart, myRichTxtBx.Document.ContentEnd);
content.Save(myFileStream, DataFormats.Xaml, true);

These are the problems with those:

1) unable to load image after restarting the application (but remembers properties)

2) does not remember the properties (but is able to load image after restarting the app)

3) won't load image not even in the same instance of the app and also does not remember the property values

I could only find answers resolving image saving issues (2) or property issues (1), but never both.

The goal is to have a tokenizable RichTextBox, where tokens are either replaced by values from database based on provided ORM object (= type-defined token) or by dynamically set values by user based again on a provided ORM object.

I have solved the issue by a very ugly workaround:

To save the document I use the method (1) described above. Before this, I traverse the FlowDocument by a custom walker and replace each image element with a custom inline token element (much like the other tokens). A hash ID is assigned as a property to this substitute element and the image itself is saved having the hash as its file name (serves to identify token with the image file). Images, along with the main document (saved by method (1)), are packaged into a single file.

When loading everything back, package is unpacked, document loaded keeping the tokens with their properties and substitute image elements are replaced by the actual images from the files saved in the package using once again the before-mentioned custom walker and the established hash token-file relation.

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