【问题标题】:Encoding text in RichTextBox from the WPF toolkit从 WPF 工具包中对 RichTextBox 中的文本进行编码
【发布时间】:2015-09-11 15:39:36
【问题描述】:

我想在 WPF 工具包的 RichTextBox 中写一些带有度数 (°) 符号的文本。

我试过了

Section section = new Section();
Paragraph paragraph = new Paragraph();
section.Blocks.Add(paragraph);
string str = string.Format("Temperature : {0:0.00}°C", temp);
text = new Run(str);
paragraph.Inlines.Add(text);
TemperatureText = System.Windows.Markup.XamlWriter.Save(section);

但是度数符号被替换为“?”。我也试过直接写unicodestring.Format("Temperature : {0:0.00}\u00B0C", temp),但也失败了。

你有什么想法吗?谢谢!

[编辑]

我正在为 RichTextBox 使用 XamlFormatter

【问题讨论】:

  • 检查是否有可以使用的属性 LangOptions。
  • 看看这个页面:它解释了如何将 Unicode 字符串转换为 RTF 转义字符串:sketchpath.blogspot.com/2007/08/rtf-and-encoding.html。还有最后一个代码示例,使用 \u00B0C,您是否要转义到 RTF?如果是,则不正确,因为您必须将 \\ 放入转义序列中才能在运行时在字符串中保留一个 \。
  • 谢谢克里斯托夫。在最后一个代码示例中,我没有转义任何内容,只是使用 unicode 十六进制作为度数符号。该标志在文本文件中很好地呈现,但在 RichTextBox 中却没有。不确定您提到的转换与此处的相关性...
  • 我相信您需要使用 RTF 转义序列,而不是转义 Unicode。假设我的预感是正确的,那么链接的文章应该可以帮助您。
  • 好的,但正如我在编辑中指出的那样,我使用的是 XamlFormatter 而不是默认的 RtfFormatter。使用 rtf 转义序列没有帮助。

标签: c# wpf utf-8 character-encoding


【解决方案1】:

尝试实现您自己的格式化程序,其作用类似于 XAMLFormatter,但使用 UTF8 编码:

public class MyXamlFormatter : ITextFormatter
{
    public string GetText( System.Windows.Documents.FlowDocument document )
    {
      TextRange tr = new TextRange( document.ContentStart, document.ContentEnd );
      using( MemoryStream ms = new MemoryStream() )
      {
        tr.Save( ms, DataFormats.Xaml );
        return Encoding.UTF8.GetString(ms.ToArray());
      }
    }

    public void SetText( System.Windows.Documents.FlowDocument document, string text )
    {
      try
      {
        if( String.IsNullOrEmpty( text ) )
        {
          document.Blocks.Clear();
        }
        else
        {
          TextRange tr = new TextRange( document.ContentStart, document.ContentEnd );
          using( MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text)))
          {
            tr.Load( ms, DataFormats.Xaml );
          }
        }
      }
      catch
      {
        throw new InvalidDataException( "Data provided is not in the correct Xaml format." );
      }
    }
}

所以,在您的 XAML 中:

<wtk:RichTextBox.TextFormatter>
    <myNameSpace:MyXamlFormatter/>
</wtk:RichTextBox.TextFormatter>

它应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 2018-12-14
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    相关资源
    最近更新 更多