2010-09-09 48 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; 
相關問題