«

»

Dec 17

How to wrap text in Silverlight TextBox Control

Rich thanks you for sharing...



 

How to allow multi-line in TextBox or TextBlock in Silverlight 5

I recently needed a multi-line TextBox box in a Silverlight 5 application. I looked at the RichTextEdit Control but it was too much for what I needed. It turns out that the TextBox control supports multi-line display and entry of text but there are a few things you need to know.

The basic TextBlock & TextBox controls with TextWrapping=”Wrap” supporting multi-line but it doesn’t support entry of “Return”.

<TextBox TextWrapping="Wrap" Text="{Binding Note}" />
<TextBlock TextWrapping="Wrap" Text="{Binding Note}" />
 

Tip: Silverlight TextBox Uses \r For New Lines, not Environment.NewLine

Silverlight has a really unusual way of handling text, and “Returns” in general. You have to specify AcceptsReturn=True to allow the user to enter return but instead of using System.Newline which consists of a return and newline special character (aka \r\n ) it uses only \r .  This can cause problems if your data needs to be normalized for other systems.

EnvironmentNewline

How can you solve the quirky behavior?  One solution is to write a normalization method like below to replace \r with \r\n.  I adapted this code from an example here.

   using System;
   using System.Text.RegularExpressions;
   namespace PHPAdmin
   {
      public static class StringExtensions 
      {
          public static string NormalizeNewLines (this string value)
         {
            if( value == null ) return value;
            return Regex.Replace( value, @"\r(?!\n)|(?<!\r)\n", Environment.NewLine );
         }
    }

 

After writing the normalize routine you can call NormalizeNewLines like below:
 
    private void Button_Click_1( object sender, RoutedEventArgs e ) 
    {
        txtInput.Text = txtInput.Text.NormalizeNewLines();
    }

 

How to allow multi-line in TextBox or TextBlock in Silverlight 5

 

So if you need to accept multi-line input from a TextBox in Silverlight be sure to normalize the input as the data may not be in the format you expect. There is a  bug listed on Microsoft Connect indicating this behavior is by design.

  • http://Maryellen.tumblr.com Jani

    It’s hard to find your page in google. I found it on 13 spot, you should build quality backlinks , it will help you to get more visitors.
    I know how to help you, just search in google – k2 seo tricks
    Jani recently posted..JaniMy Profile