wpf textbox limit text

Angela4eva used Ask the Experts™
I have text box in wpf xaml and I want the user to not be able to enter more than 60 characters.. when the starts typing it should tell tem how many charcters they have left to type when they copy paste let them not paste it. I am new to wpf any help appreciated
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Set the MaxLength property of the textbox to 60.

Add a label after the textbox and create an event for the textbox.TextChanged event set the Label.Text to be textbox.MaxLength - textbox.Text.Length + " Characters remaining"

With the MaxLength property set I wouldn't worry about being able to paste it will still only allow 60 chars

Code samples:


<TextBox Height="23" Name="textbox1" VerticalAlignment="Top" MaxLength="60" TextChanged="textbox1_TextChanged" />
<Label Content=""  Height="37" HorizontalAlignment="Left" Name="label1" VerticalAlignment="Top" Width="197.963" />

Open in new window

xaml.cs (sorry if your not using c#)

        private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
            label1.Content = (textbox1.MaxLength - textbox1.Text.Length).ToString() + " chars remaining";

Open in new window


great solution. thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial