C# 在WPF工具包的RichTextBox中编码文本

C# 在WPF工具包的RichTextBox中编码文本,c#,wpf,utf-8,character-encoding,C#,Wpf,Utf 8,Character Encoding,我想在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.A

我想在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);
但学位符号被替换为“?”。我还尝试直接编写unicode
string.Format(“温度:{0:0.00}\u00B0C”,temp)
,但也失败了

你知道吗?谢谢

[编辑]


我正在为RichTextBox使用XamlFormatter

尝试实现您自己的格式化程序,它与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>


它应该可以工作。

检查是否有可以使用的属性LangOptions。查看此页面:它解释了如何将Unicode字符串转换为RTF转义字符串:。最后一个代码示例是\u00B0C,您是否正在尝试转义到RTF?如果是,则不正确,因为在运行时必须将\\放入转义序列以在字符串中保留一个\项。谢谢Christoph。在上一个代码示例中,我没有转义任何内容,只是使用unicode十六进制作为度符号。符号在文本文件中呈现良好,但在RichTextBox中呈现不好。我不确定您提到的转换在这里是如何相关的……我认为您需要使用RTF转义序列,而不是转义Unicode。假设我的直觉是正确的,这就是链接文章应该帮助你的地方。好吧,但正如我在编辑中指出的,我使用的是XamlFormatter,而不是默认的RTF格式。使用rtf转义序列没有帮助。