我在我的窗口中使用richtextbox,这里输入一个字符串,这个字符串将是 xmal 字符串,在这里我需要粘贴字符串,格式与我输入的相同...我有一个代码表stackoverflow但它只适用于一个如果XAMLstring有多个段落意味着它不工作,这里的示例XMALstring工作和不工作。
工作:
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>";
不适用于:
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>";
这里我的代码是:
XmlReader xmlReader = XmlReader.Create(new StringReader(xamlString));
Paragraph template1 = (Paragraph)XamlReader.Load(xmlReader);
newFL.Blocks.Add(template1);
RichTextBox1.Document = newFL;
答案 0 :(得分:1)
由于xamlString包含FlowDocument,因此XamlReader.Load将返回FlowDocument对象而不是Paragraph。如果您想处理各种内容,可以执行以下操作:
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;