Friday, August 19, 2011

Simulating MaxLines property in Silverlight TextBox

You must have noticed that Silverlight TextBox control is missing the infamous MaxLines property which is a quite useful property in WPF TextBox and that's why you're reading this. 

I have had this requirement since last week about putting a limit on the number of lines you can write in a multiline (AcceptsReturn=true) TextBox in Silverlight 4 and was disappointed to know that there is currently no way you do it like in WPF. In WPF, the TextBox control has an integer property called MaxLines which you can set to limit the number of lines. In Silverlight, there seems to be no way because you wouldn't possibly know when or where in the string a word wrap split has occurred. It would be simple if you are using a fixed-width font like Courier/CourierNew because you can simply count the number of characters that would fit in one line, but in my case, its Comic Sans. The client insisted that they wanted this feature so I decided to write my own logic to simulate the word wrap algorithm used in Silverlight TextBoxes. So I had no choice but to take the challenge. 

Read More from: Original Source