#918 – Limiting How Much Text a User Can Enter into a TextBox

You can use the MaxLength property of a TextBox to indicate the maximum number of characters that a user is allowed to enter.

In the example below, we limit the hobo name to a max of 10 characters.

    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <Label Content="Enter your hobo name:"/>
        <TextBox Grid.Column="1" MaxLength="10"/>
    </Grid>

918-001
The MaxLength also applies to text that you paste into the TextBox.  The pasted text will be clipped based on the current value of MaxLength.  

By default, MaxLength has a value of 0, which indicates that there is no effective maximum length for text entered or pasted into the control.  (If a user continued entering text indefinitely, the application would eventually run out of memory).

Advertisement