且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 XAML 转换为 FlowDocument 以在 WPF 中的 RichTextBox 中显示

更新时间:2022-12-26 22:13:14

我认为它会在 Add() 上崩溃,因为您正在添加一个已经具有逻辑的 FrameworkContentElement父母.您必须首先从其父项中删除 Block,然后才将其添加到不同的集合中.试试这个:

I assume it crashes on Add() because you are adding a FrameworkContentElement which already has a logical parent. You must first remove a Block from its parent and only then add it to a different collection. Try this:

private static FlowDocument SetRTF(string xamlString)
{
    StringReader stringReader = new StringReader(xamlString);
    System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
    Section sec = XamlReader.Load(xmlReader) as Section;
    FlowDocument doc = new FlowDocument();
    while (sec.Blocks.Count > 0)
    {
        var block = sec.Blocks.FirstBlock;
        sec.Blocks.Remove(block);
        doc.Blocks.Add(block);
    }
    return doc;
}

如果您的 XAML 已经代表 FlowDocument

然后事情就简单多了.做一个:

If your XAML already represents a FlowDocument

Then things are much simpler. Just do a:

    private static FlowDocument SetRTF(string xamlString)
    {
        StringReader stringReader = new StringReader(xamlString);
        System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
        return XamlReader.Load(xmlReader) as FlowDocument;
    }

用法

richTextBox.Document = SetRTF(xamlString);