am using richtextbox in my window and here am getting an input as a string ,this string will be xmal string and here i need to paste the string with a same format what i entered ...i got a code form stackoverflow but it works for only one if the XAMLstring has more than one paragraph means it is not working ,here the example XMALstring for both working and not working.
Working For:
string xamlString = "<Paragraph xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TextAlignment=\"Left\"><Run FontFamily=\"Comic Sans MS\" FontSize=\"16\" Foreground=\"#FF0000FF\" FontWeight=\"Bold\" >This text is blue and bold.<开发者_运维技巧/Run></Paragraph>";
Not Working For:
string xamlString = "<FlowDocument xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Paragraph><Run FontSize=\"14px\">Hai this is a Testing</Run></Paragraph><Paragraph><Run FontStyle=\"italic\" FontSize=\"12.5px\" FontWeight=\"bold\">Test</Run></Paragraph></FlowDocument>";
And here my code is:
XmlReader xmlReader = XmlReader.Create(new StringReader(xamlString));
Paragraph template1 = (Paragraph)XamlReader.Load(xmlReader);
newFL.Blocks.Add(template1);
RichTextBox1.Document = newFL;
Since that xamlString contains a FlowDocument, XamlReader.Load will return a FlowDocument object rather than a Paragraph. If you want to handle various kinds of content, you could do something like this:
XmlReader xmlReader = XmlReader.Create(new StringReader(xamlString));
object template1 = XamlReader.Load(xmlReader);
FlowDocument newFL;
if (template1 is FlowDocument)
{
newFL = (FlowDocument)template1;
}
else
{
newFL = new FlowDocument();
if (template1 is Block)
{
newFL.Blocks.Add((Block)template1);
}
else if (template1 is Inline)
{
newFL.Blocks.Add(new Paragraph((Inline)template1));
}
else if (template1 is UIElement)
{
newFL.Blocks.Add(new BlockUIContainer((UIElement)template1));
}
else
{
// Handle unexpected object here
}
}
RichTextBox1.Document = newFL;
精彩评论