To do DataBinding of the Document
in a WPF RichtextBox
, I saw 2 solutions so far, which are to derive from the RichtextBox
and add a DependencyProperty
, and also the solution with a "proxy".
Neither the first or the second are satisfactory. Does somebody know another solution, or instead, a commercial RTF control which is capable of DataBinding? The normal TextBox
is not an alternative, since we need text formatting.
Any idea?
Best Answer
There is a much easier way!
You can easily create an attached
DocumentXaml
(orDocumentRTF
) property which will allow you to bind theRichTextBox
's document. It is used like this, whereAutobiography
is a string property in your data model:Voila! Fully bindable
RichTextBox
data!The implementation of this property is quite simple: When the property is set, load the XAML (or RTF) into a new
FlowDocument
. When theFlowDocument
changes, update the property value.This code should do the trick:
The same code could be used for TextFormats.RTF or TextFormats.XamlPackage. For XamlPackage you would have a property of type
byte[]
instead ofstring
.The XamlPackage format has several advantages over plain XAML, especially the ability to include resources such as images, and it is more flexible and easier to work with than RTF.
It is hard to believe this question sat for 15 months without anyone pointing out the easy way to do this.