Http://fqctyj.blog.163.com/blog/static/70843455200810812410361/
Some people have been asking me how to save the RichTextBox text to the database over the past few days, including the format and so on, and then retrieve it from the database and display it in RichTextBox.
In fact, RichTextBox text is a flowdocument object. We only need to use xamlreader and xamlwriter to complete the above work.
[Save document to stream]
Flowdocument document = RichTextBox. Document;
Stream S = new memorystream (); // no other stream types.
Xamlwriter. Save (document, S );
// After S is obtained, it is OK to convert binary data into binary data and write it to the database.
Byte [] DATA = new byte [S. Length];
S. Position = 0;
S. Read (byte, 0, S. Length );
S. Close ();
// Whatever data you want
//......
[Read from database]
// Data is the binary data read from the database.
Stream S = new memorystream (data );
Flowdocument Doc = xamlreader. load (s) as flowdocument;
S. Close ();
RichTextBox. Document = Doc;
PS: someone asked me how to bind the document attribute of RichTextBox. Because the document attribute of RichTextBox is not a dependencyproperty,
So what I use is to inherit RichTextBox and define a dependencyproperty of bindabledocument.
Publicclasspublicget {return (flowdocument) getvalue (textproperty);} set {setvalue (textproperty, value);} // using a dependencyproperty as the backing store for text. this enables animation, styling, binding, etc
Publicstaticreadonly dependencyproperty textproperty =
Dependencyproperty. Register ("bindabledocument", typeof (flowdocument), typeof (bindablerichtextbox), new uipropertymetadata (null, new propertychangedcallback (ontextpropertychanged )));
Privatestaticvoid ontextpropertychanged (dependencyobject sender, dependencypropertychangedeventargs E)
{
Bindablerichtextbox textbox = sender Asif (textbox! = Null {
Textbox. _ changefrombinding = true;
Textbox. ontextpropertychanged (E );
} // Prevent deadlocks. For example, if a changes to notification B, if B changes, it notifies.
Privatebool _ changefrombinding = false // notifies the document attribute when the bindabledocument attribute changes
Protectedvirtualvoid ontextpropertychanged (dependencypropertychangedeventargs E)
Ifthis. Document = E. newvalue as // when the document attribute changes, the bindabledocument attribute is notified.
Protectedoverrisponid ontextchanged (textchangedeventargs E)
Baseif (! This. bindabledocument = this // put it outside
_ Changefrombinding = false
Make a smallProgram, Binds the text of A textbox to RichTextBox. Download