代码之家  ›  专栏  ›  技术社区  ›  Andrija

将RTF文本设置到WPF RichTextBox控件中

  •  36
  • Andrija  · 技术社区  · 16 年前

    我有这个RTF文本:

    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial;}}
    {\colortbl ;\red0\green0\blue0;\red255\green0\blue0;}
    \viewkind4\uc1\pard\qc\cf1\fs16 test \b bold \cf2\b0\i italic\cf0\i0\fs17 
    \par }
    

    WPF RichTextBox


    解决方案:

    public void SetRTFText(string text)
    {
        MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(text));
        this.mainRTB.Selection.Load(stream, DataFormats.Rtf);
    }
    
    4 回复  |  直到 5 年前
        1
  •  38
  •   Henk Holterman    16 年前

    你真的必须从字符串开始吗?

    rtfBox.Selection.Load(myStream, DataFormats.Rtf);
    

    但我在等有人想出更优雅的东西。

        2
  •  5
  •   Ross    10 年前

        public static void SetRtf(this RichTextBox rtb, string document)
        {
            var documentBytes = Encoding.UTF8.GetBytes(document);
            using (var reader = new MemoryStream(documentBytes))
            {
                reader.Position = 0;
                rtb.SelectAll();
                rtb.Selection.Load(reader, DataFormats.Rtf);
            }
        }
    

    richTextBox1.SetRtf(rtf);

        3
  •  1
  •   Rhyous    15 年前
    string rtf = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial;}} {\colortbl ;\red0\green0\blue0;\red255\green0\blue0;} \viewkind4\uc1\pard\qc\cf1\fs16 test \b bold \cf2\b0\i italic\cf0\i0\fs17  \par } ";
    richTextBox1.Rtf = rtf;
    

        4
  •  1
  •   kayess    8 年前

    编辑 :此答案假定WinForms而不是WPF。

    string rtf = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial;}} {\colortbl ;\red0\green0\blue0;\red255\green0\blue0;} \viewkind4\uc1\pard\qc\cf1\fs16 test \b bold \cf2\b0\i italic\cf0\i0\fs17  \par } ";
    richTextBox1.Rtf = rtf;
    
        5
  •  -3
  •   J. Random Coder    16 年前
    推荐文章