Reputation: 1
I am building a chat application and I am receiving xaml string that I would like to display in my RichtextBox(chatBox) as formatted text. This is what I managed to do so far.
How to display received xaml string as formatted text in Richtextbox in chat application?
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 )))));
}
This is how I send message(displaying sent message as formatted string works well)
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);
}
and This is how I manage to convert string text** text to 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;
}
Upvotes: 0
Views: 487
Reputation: 128098
Serialize the Document
of a RichTextBox like this:
var xaml = XamlWriter.Save(richTextBox.Document);
Deserialize it like this:
richTextBox.Document = XamlReader.Parse(xaml) as FlowDocument;
Upvotes: 1