有备考软考的小伙伴,想积分落户,单位评职称?科目太多不知道怎么选?考试考点难点太多没有头绪?刚准备1个多月过了高级,关注我,我整理了软考各科目的报考条件、适合人群以及备考攻略,可以直接领取:
https://d.51cto.com/eDOcp1
这几天一直有人问我如何保存RichTextBox的文本到数据库,包括格式等等,然后需要的再从数据库取出来,并且显示到RichTextBox中。
其实,RichTextBox的文本是一个FlowDocument类型的对象,我们只需要利用XamlReader和XamlWriter就能很好的完成上述工作。
【保存Document到流】
FlowDocument document = richTextBox.Document;
Stream s = new MemoryStream(); // 其他的什么Stream类型都没问题
XamlWriter.Save(document, s);
// 拿到s之后,再转化成二进制数据写到数据库就OK了
byte[] data = new byte[s.Length];
s.Position = 0;
s.Read(byte, 0, s.Length);
s.Close();
// 拿着data干啥都行
// ……
【从数据库中读取】
// data是从数据库中读出来的二进制数据
Stream s = new MemoryStream(data);
FlowDocument doc = XamlReader.Load(s) as FlowDocument;
s.Close();
richTextBox.Document = doc;
PS:有人问过我如何对RichTextBox的Document属性做绑定,由于RichTextBox的Document属性不是一个DependencyProperty,
所以我采用的是继承RichTextBox,自己定义一个BindableDocument的DependencyProperty来做。
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);
}// 防止死锁,比如A变了通知B,B变了又通知A
privatebool _changeFromBinding =false// 当BindableDocument属性变化时,通知Document属性
protectedvirtualvoid OnTextPropertyChanged(DependencyPropertyChangedEventArgs e)
ifthis.Document = e.NewValue as// 当Document属性变化时,通知BindableDocument属性
protectedoverridevoid OnTextChanged(TextChangedEventArgs e)
baseif (!this.BindableDocument =this// 放到外面
_changeFromBinding =false
做了个小程序,绑定了一个TextBox的Text到RichTextBox。 下载
有备考软考的小伙伴,想积分落户,单位评职称?科目太多不知道怎么选?考试考点难点太多没有头绪?刚准备1个多月过了高级,关注我,我整理了软考各科目的报考条件、适合人群以及备考攻略,可以直接领取:
https://d.51cto.com/eDOcp1
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
赞 收藏 评论 举报相关文章
【Mybatis】-数据库如何实现数据封装(以及增、更、查) 新增//新增@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" + "value (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptIdTest 封装 主键 数据封装