【问题标题】:c# wpf export RichTextBox formatting to xml documentc# wpf将RichTextBox格式导出到xml文档
【发布时间】:2017-04-21 09:11:42
【问题描述】:

所以在 WPF 中我创建了一个 RichTextBox 并实现了能够格式化所选文本(粗体、未划线、字体等)的功能,但现在我想将所有格式导出到 XML文件,所以当我加载它时,加载的文件会给我相同格式的相同文本。 我认为最好的方法是,如果我能在 RTB 中找到每个有格式的地方,然后将其保存为文本范围,但我不知道 RTB 是否有方法来查找文本的一部分已格式化。

这是我所拥有的: xml:

<Button Name = "export" Click = "export_Click"/>
<RichTextBox x:Name="RTB"/>

和c#:

private void export_Click(object sender, RoutedEventArgs e){
    TextRange range = new TextRange();
    //here is where i want to access the formatted areas
    //something like: range = RTB.document.getBoldArea();
    //and then i could export what i got in the text range to a xml file
}

提前感谢任何愿意提供帮助的人!

【问题讨论】:

    标签: c# xml wpf formatting richtextbox


    【解决方案1】:

    您实际上可以直接访问 XAML 内容,它本身显然是 XML。您可以直接保存它,也可以将其操作/翻译成您自己的架构。

    获取 RichTextBox 的 XAML:

    static string GetXaml(RichTextBox rt)
    {
        TextRange range = new TextRange(rt.Document.ContentStart, rt.Document.ContentEnd);
        MemoryStream stream = new MemoryStream();
        range.Save(stream, DataFormats.Xaml);
        string xamlText = Encoding.UTF8.GetString(stream.ToArray());
        return xamlText;
    }
    

    为 RichTextBox 设置 XAML 内容:

    static void SetXaml(RichTextBox rt, string xamlString)
    {
        StringReader stringReader = new StringReader(xamlString);
        XmlReader xmlReader = XmlReader.Create(stringReader);
        Section sec = XamlReader.Load(xmlReader) as Section;
        FlowDocument doc = new FlowDocument();
        while (sec.Blocks.Count > 0)
            doc.Blocks.Add(sec.Blocks.FirstBlock);
        rt.Document = doc;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 1970-01-01
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多