如何将XAMLstring更改为XMAL代码以粘贴到WPF中的RichTextBox中?

如何将XAMLstring更改为XMAL代码以粘贴到WPF中的RichTextBox中?,wpf,Wpf,我在我的窗口中使用richtextbox,这里我得到一个作为字符串的输入,这个字符串将是xmal字符串,这里我需要用我输入的相同格式粘贴字符串…我得到了一个代码表单stackoverflow,但如果XAMLstring有多个段落意味着它不工作,它只对一个有效,这里的示例XMALstring用于工作和不工作 工作地点: string xamlString = "<Paragraph xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/pr

我在我的窗口中使用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>";

由于该xamlString包含一个FlowDocument,因此XamlReader.Load将返回一个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;

由于该xamlString包含一个FlowDocument,因此XamlReader.Load将返回一个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;