RichTextBox Text property where are you hiding?

Today I was playing around with the RichTextBox and I found out something the hard way…. There is no Text property. I started googling about this and I found out that instead of a Text property there is a Document property that returns a FlowDocument. This is really cool because it means that we can have all the goodies of a flow document in our RichTextBox but the big question for me was still how do I get what the user entered in a simple string??

Well the answer lies in 1 line of code :)

   1: new TextRange(myTextBox.Document.ContentStart, myTextBox.Document.ContentEnd).Text

So what we are doing here is just reading the FlowDocument content and getting a string out of it.

This is all cool but then I needed something else. I wanted to bind the RichTextBox to a String property in an object. First I tried with a converter, but guess what the Document property of the RichTextBox is not a Dependency object thus I could not bind and do a converter that returns a FlowDocument.

No worries…. With WPF there is always a way out :)

I created an Attached property called Text that will add a string in the RichTextBox default FlowDocument. Here is how I did it

   1: private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

   2: {

   3:     RichTextBox textBox = (RichTextBox)d;

   4:     if (e.NewValue != null)

   5:     {

   6:         textBox.Document.Blocks.Clear();

   7:         textBox.Document.Blocks.Add(new Paragraph(new Run(e.NewValue.ToString())));

   8:     }

   9: }

The behavior I chose was to clear any other text from the TextBox and replace it with the string that is supplied. Obviously this is really easy to change, you just have to change the textBox.Document.Blocks.Clear()

RichTextBox is really an impressive control… I fell in love with it (and yea let’s not forget SpellCheck.IsEnabled="True" which is one of my new favorite goodies :) ) so don’t let something as simple as the Text property keep you away from using such a powerful control :)

I created a sample project with some example source code that you can download.