Getting the total number of characters (count) from a Silverlight text box.

Let’s say that we have a requirement where we should restrict the users to enter only a certain number of characters (let’s say 150) in a TextBox of a Silverlight usercontrol. We will see how to achieve that in Silvelright.

1. Create a Silverlight project and add a Text Box in to it as shown below.

<TextBox Height="100" Width="600" FontSize="20" HorizontalAlignment="Left" TextChanged="tbPost_TextChanged" Name="tbPost" AcceptsReturn="True" TextWrapping="Wrap" VerticalAlignment="Top"  />

as seen above we have set its height and width to a large number to make it look like a RichTextBox, we have also added a Event Handler called tbPost_TextChanged for TextChanged Event and also the AcceptsReturn has been set to true for multiline functionality.

2. Add a TextBlock below the TextBox to display the number of characters being entered in to the TextBox.

<TextBlock FontFamily="Tahoma" Name="tblkCharLeft" Width="150" HorizontalAlignment="Left" FontSize="12" FontWeight="Light" >

3. In the MainPage.xaml.cs write the following code in the tbPost_TextChanged  event.

private void tbPost_TextChanged(object sender, TextChangedEventArgs e)
            count = 150 - tbPost.Text.Count();
            tblkCharLeft.Text = Convert.ToString(count);

            tblkCharLeft.Foreground = count  > 150 ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Black);

4. In the above code, we are getting the number of characters in the Text Box and subtracting it from 150(which is the total number of characters allowed) and storing the result in an Integer variable called count. And then display the number in the Text Block.

5. In the last line we are changing the Foreground of the Text block to Red color after checking if the value of the integer variable count is greater than 150 using tertiary operator.

6. When you build and run the application. You can see that, as you type in the text box the number of characters in the text box gets displayed in the text block.

7. The color of the text in the text block gets changed when the number goes more than 150 as shown in the below screenshot.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s