A WPF FlowDocument
can only belong to a single RichTextBox
. However, we'd like to use a single document which can be manipulated at different points (in space and time) in the UI. It will never happen that there are two RichTextBoxes
simultaneously displaying a single document (and can't, because WPF will complain).
Using a MemoryStream
and XamlReader
/Writer
won't work here as we would like to retain a single document and reflect changes wherever it is used, so copying it every time is out.
Is there any other viable way to achieve that? Something you could use as underlying model from which to create FlowDocument
s or so?
Clarification: The RichTextBoxes that use the Document are no longer visible or anywhere in the logical/visual tree when another one will be instantiated. Though I probably can't enforce that they have already been eaten by the GC. Seemingly this causes a problem when re-using the Document immediately after removing the RichTextBox from the window; that still throws an exception that the Document is already used in another control.
Basically be have a set of "wizard pages" that are displayed one after another and it can happen that we re-use the Document on two successive "pages" but instantiate a new RTBox each time. Maybe there's a problem or a better way?
Depending on how your wizard is constructed I actually would recommend you simply move the RichTextBox from page to page. WPF controls can be ‘unparented’ and ‘reparented’ at will, so just make the RichTextBox instance available in the context shared throughout your wizard and make sure you unparent / reparent as you move from page to page. This also has the benefit of saving any styles or changes to the editors state across pages in the wizard (which is probably desirable).
If it isn’t possible to share the RichTextBox instance across pages, I think there is a way to disassociate the document from the original RichTextBox. It appears that in order to disassociate the document from RichTextBox1, you have to provide RichTextBox1 with a new document. You can’t set RichTextBox1.Document to null, but you CAN set RichTextBox1.Document to new FlowDocument() and I believe that will work. I’m unable to test this right now, but I saw it was recommended in the last post of this MSDN forum thread:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/797bfc96-cf24-4071-bff8-ce8c4a7b897b