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 :)
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
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 :)