2010-09-09 64 views
1

我在我的窗口中使用richtextbox,这里得到一个字符串输入,这个字符串将是xmal字符串,在这里我需要粘贴与我输入的格式相同的字符串...我得到了一个代码表单stackoverflow但如果XAMLstring有多个段落意味着它不起作用,那么它只适用于一个,这里是工作和不工作的示例XMALstring。如何将XAMLstring更改为XMAL代码以粘贴到WPF中的RichTextBox中?

工作:

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; 

回答

1

自那xamlString包含的FlowDocument,XamlReader 。加载将返回一个FlowDocument对象而不是段落。如果你想处理各种内容,你可以这样做:

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; 
相关问题