【问题标题】:Can the WPF RichTextBox content be serialized without FontFamily and FontSize?可以在没有 FontFamily 和 FontSize 的情况下对 WPF RichTextBox 内容进行序列化吗?
【发布时间】:2015-04-12 07:11:08
【问题描述】:

就像您在 StackOverflow 上看到的编辑器一样,我希望用户能够指定他们的部分文本应该是粗体、斜体或下划线,但我不希望他们能够设置字体大小或字体系列;这些需要从可视化树中的其他位置继承。

当将 WPF RichTextBox 控件放入空窗口并提供几个字符的文本时,富文本的序列化表示始终包括 FontFamily。例如,在 LINQPad 中:

void Main()
{
    var window = new Window();
    var editor = new RichTextBox();
    window.Content = editor;
    window.ShowDialog();

    var rtf = RtfUtility.ConvertToRtf(editor.Document);
    rtf.Dump();
}

我输入了“你好,世界!”进入 RichTextBox。

{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\ltrch HELLO, WORLD!}\li0\ri0\sa0\sb0\fi0\ql\par}}}

RTF序列化代码没什么特别的:

var range = new TextRange(document.ContentStart, document.ContentEnd);
using (var stream = new MemoryStream())
{
    range.Save(stream, DataFormats.Rtf);
    stream.Position = 0;
    using (var reader = new StreamReader(stream, Encoding.UTF8))
        return reader.ReadToEnd();
}

序列化表示同时引用 Times New RomanSegoe UI,但这是不可取的。

是否可以呈现富文本并从其他地方继承字体系列和大小,以及在没有这些属性的情况下对其进行序列化?

我想另一种方法是在每次反序列化文本时将 FontFamily 和 FontSize 设置为我想要的任何值 - 但这看起来很老套。如果可行,我也愿意接受不涉及 RichTextBox 的完全不同的解决方案。

【问题讨论】:

    标签: wpf richtextbox rtf flowdocument


    【解决方案1】:

    FlowDocument 假定 Sergoe UI 作为默认字体。此字体采用 FlowDocument 对象的样式。

    要改变这个:

    editor.Document.FontFamily = new FontFamily("Times New Roman");
    editor.Document.FontSize = 12;
    

    您还可以使用 App.xaml 中的 xaml 声明或以编程方式为每个 FlowDocument 创建所有 FlowDocument 的样式:

    var style = new Style(typeof(FlowDocument));
    style.Setters.Add(new Setter(FlowDocument.FontFamilyProperty, new FontFamily("Times New Roman")));
    style.Setters.Add(new Setter(FlowDocument.FontSizeProperty, 12));
    editor.Resources.Add(typeof(FlowDocument), style)
    

    在为段落创建样式(new Style(typeof(Paragraph)))时,您还可以更改每个单独段落的设置。

    不幸的是,序列化保存了 FlowDocument 的资源和所有未继承的设置。

    【讨论】:

    • 当 RichTextBox 开始为空时,我绝对可以将 FontFamily/FontSize 设置为我想要的任何值,但如果我正在编辑已反序列化的文本,这将不起作用。除非有更好的解决方案,否则我似乎必须深入研究所有文档元素并清除所有 FontFamily/FontSize 规范。
    【解决方案2】:

    您可以使用文本范围:

    TextRange tr2 = new TextRange(mergedDocument.ContentStart, mergedDocument.ContentEnd);
            tr2.ApplyPropertyValue(Span.FontFamilyProperty, font);
            tr2.ApplyPropertyValue(Span.FontSizeProperty, "24");
            tr2.ApplyPropertyValue(List.FontFamilyProperty, font);
            tr2.ApplyPropertyValue(List.FontSizeProperty, "24");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      相关资源
      最近更新 更多