Set RTF text into WPF RichTextBox control

前端 未结 5 1189
一个人的身影
一个人的身影 2021-01-31 08:44

I have this RTF text:

{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Arial;}}
{\\colortbl ;\\red0\\green0\\blue0;\\red255\\green0\         


        
相关标签:
5条回答
  • 2021-01-31 09:02
    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;
    

    It's working fine

    0 讨论(0)
  • 2021-01-31 09:11

    Create an Extension method

        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);
            }
        }
    

    Then you can do WinForm-esque style

    richTextBox1.SetRtf(rtf);

    0 讨论(0)
  • 2021-01-31 09:12

    Edit: This answer assumes WinForms instead of WPF.

    Simply use RichTextBox.Rtf:

    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;
    
    0 讨论(0)
  • 2021-01-31 09:18

    I wrote a really slick solution by extending the RichTextBox class to allow Binding to an actual rich text file.

    I came across this question/answer but didn't really get what I was looking for, so hopefully what I have learned will help out those who read this in the future.

    Loading a RichTextBox from an RTF file using binding or a RichTextFile control

    0 讨论(0)
  • 2021-01-31 09:24

    Do you really have to start with a string?

    One method to load RTF is this:

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

    You probably should call SelectAll() before that if you want to replace existing text.

    So, worst case, you'll have to write your string to a MemoryStream and then feed that stream to the Load() method. Don't forget to Position=0 in between.

    But I'm waiting to see somebody to come up with something more elegant.

    0 讨论(0)
提交回复
热议问题