我是wpf的新手,我想将富文本框的数据及其格式(斜体,彩色,粗体..)存储到数据库(Mysql)中。目前,当我保存数据时,格式化将被忽略。此外,当我将其从数据库加载回富文本框时,它会在同一行中显示所有文本。期待您的帮助和建议!
public void save() { MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); string richText = new TextRange(rt1.Document.ContentStart, rt1.Document.ContentEnd).Text; string s = WebUtility.HtmlEncode(richText); command.Parameters.AddWithValue("@s", s); command.CommandText = "insert into proc_tra (procedures) values (@s)"; conn.Open(); command.ExecuteNonQuery(); conn.Close(); } public void load() { MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); command.CommandText = "select * from proc_tra where id_pt=4"; rt1.Document.Blocks.Clear(); conn.Open(); MySqlDataReader dr; dr = command.ExecuteReader(); string k=""; while (dr.Read()) { k += dr["procedures"].ToString(); } var p = new Paragraph(); var run = new Run(); run.Text = WebUtility.HtmlDecode(k); p.Inlines.Add(run); rt1.Document.Blocks.Add(p); }
要获取将保存在数据库中的格式化文本:
string rtfText; //string to save to db TextRange tr = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); using (MemoryStream ms = new MemoryStream()) { tr.Save(ms, DataFormats.Rtf); rtfText = Encoding.ASCII.GetString(ms.ToArray()); }
要恢复从数据库检索到的格式化文本,请执行以下操作:
string rtfText= ... //string from db byte[] byteArray = Encoding.ASCII.GetBytes(rtfText); using (MemoryStream ms = new MemoryStream(byteArray)) { TextRange tr = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); tr.Load(ms, DataFormats.Rtf); }
您还可以改用XAML格式,在加载保存时使用DataFormats.XAML。