Monday, October 4, 2010

WPF - RichText Box - How to set Text

Recently at work, I come across a need to use RichTextBox control. My project is on WPF. I need to set/get some data on/from RichTextBox control programmatically so that I decided I would use the Text property of RichTextBox Control. Sounds like piece of cake, correct?

RichTextBox control is part of System.Windows.Forms and System.Windows.Control. Since I am working of WPF therefore I am using this control from System.Windows.Control namespace.

To my surprise I found that there is no Text property on RichTextBox control.

After struggling with it for sometime here is what I found to set some text on RichTexbox control in WPF

// Create a FlowDocument to contain content for the RichTextBox.
FlowDocument myFlowDoc = new FlowDocument();

// Add paragraphs to the FlowDocument.
myFlowDoc.Blocks.Add(new Paragraph(new Run("Test Paragraph 1")));
myFlowDoc.Blocks.Add(new Paragraph(new Run("Test Paragraph 2")));
myFlowDoc.Blocks.Add(new Paragraph(new Run("Test Paragraph 3")));
RichTextBox myRichTextBox = new RichTextBox();

// Add initial content to the RichTextBox.
myRichTextBox.Document = myFlowDoc;

If you want to set some text on a RichTextBox control in design mode then you can do something like:

<richtextbox margin="10,10,0,13" name="RichTextBox1" horizontalalignment="Left" verticalalignment="Top" width="500" height="300">
<flowdocument>
    <paragraph>
      Test Paragraph 1
    </paragraph>
    <paragraph foreground="Red">
      Test Paragraph 2 in red.
    </paragraph >
</flowdocument >
</richtextbox >

No comments:

Recent Posts