2010-09-09 4 views
1

suis en utilisant richtextbox dans ma fenêtre et ici je reçois une entrée en tant que chaîne, cette chaîne sera xmal chaîne et ici je dois coller la chaîne avec un même format ce que je suis entré ... j'ai reçu un code stackoverflow mais cela ne fonctionne que pour un si le XAMLstring a plus d'un paragraphe signifie qu'il ne fonctionne pas, ici l'exemple XMALstring pour travailler et ne pas fonctionner.Comment changer la chaîne XAMLstring en code XMAL pour coller dans la RichTextBox dans WPF?

Travailler Pour:

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>"; 

ne fonctionne pas avec:

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>"; 

Et voici mon code est:

XmlReader xmlReader = XmlReader.Create(new StringReader(xamlString)); 
Paragraph template1 = (Paragraph)XamlReader.Load(xmlReader); 
      newFL.Blocks.Add(template1); 
RichTextBox1.Document = newFL; 

Répondre

1

Depuis xamlString contient un FlowDocument, XamlReader . Load retournera un objet FlowDocument plutôt qu'un paragraphe. Si vous souhaitez gérer différents types de contenu, vous pouvez faire quelque chose comme ceci:

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; 
Questions connexes