如何在RichTextBox中将Xaml消息显示为格式化文本

时间:2016-05-05 16:30:39

标签: c# wpf chat

我正在构建一个聊天应用程序,我正在接收xaml字符串,我想在我的RichtextBox(chatBox)中显示为格式化文本。这是我到目前为止所做的。

如何在聊天应用程序的Richtextbox中将收到的xaml字符串显示为格式化文本?

        while (true)
         {

                        recv = ns.Read(data, 0, data.Length);
                        msg = Encoding.UTF8.GetString(data, 0, recv);

                        StringReader stringReader = new StringReader(msg);////interpretacja xaml reader
                        XmlReader xmlReader = XmlReader.Create(stringReader);//xaml reader
                        Section sec = XamlReader.Load(xmlReader); 
    chatBox.Dispatcher.BeginInvoke((Action)(() => chatBox.Document.Blocks.Add(new Paragraph(new Run("partner "+time+":\n" + msg )))));
}  

这是我发送消息的方式(显示已发送消息的格式化字符串效果很好)

void buttonlick()
{
 string msg = RTFfromat.GetRTF(messageBox);//konwersja wiadomosc na xaml string

            messageBox.Document.Blocks.Clear();


            ///intepreting xaml message
            StringReader stringReader = new StringReader(msg);////interpretacja xaml reader
            XmlReader xmlReader = XmlReader.Create(stringReader);//xaml reader
            Section sec = XamlReader.Load(xmlReader) as Section;/////

            // send msg
            ns.Write(Encoding.UTF8.GetBytes(msg), 0, msg.Length);
            ns.Flush();


            //change background color
            sec.SetValue(Paragraph.BackgroundProperty, Brushes.LightSkyBlue);

            //adding formatted text message nto chatbox
            chatBox.Document.Blocks.Add(sec.Blocks.FirstBlock);
}

这就是我设法将字符串文本**文本转换为xaml String

的方法
public static string GetRTF(RichTextBox rt)
        {
            TextRange range = new TextRange(rt.Document.ContentStart, rt.Document.ContentEnd);
            MemoryStream stream = new MemoryStream();
            range.Save(stream, DataFormats.Xaml);
            string xamlText = Encoding.UTF8.GetString(stream.ToArray());
            return xamlText;
        } 

1 个答案:

答案 0 :(得分:1)

像这样序列化RichTextBox的Document

var xaml = XamlWriter.Save(richTextBox.Document);

将其反序列化为:

richTextBox.Document = XamlReader.Parse(xaml) as FlowDocument;