17

How would I set the number of characters a user is allowed to input in a TextBlock in xaml?

Would I do it on the Model or create some sort of custom attribute to handle it?

griegs
  • 22,624
  • 33
  • 128
  • 205
  • Does this answer your question? [Can you limit the length of Text visible in a WPF TextBlock?](https://stackoverflow.com/questions/7170817/can-you-limit-the-length-of-text-visible-in-a-wpf-textblock) – StayOnTarget May 05 '20 at 19:22

4 Answers4

14

TextBlock doesn't have a MaxLength, neither does Label. TextBox does. Users cannot input into a TextBlock unless you have modified it.

Is it really a TextBlock you want to limit or did you mean a TextBox? If it is a TextBox you can simply use the MaxLength property.

<TextBox Name="textBox1" MaxLength="5" />

If it really is a TextBlock you are using and somehow allowing a user to input data into it, then switch to use a TextBox. If it is the TextBlock style you are after, you can style the TextBox to look like a TextBlock.

Rhyous
  • 6,510
  • 2
  • 44
  • 50
11

Without creating a custom control, you have a few options.

You could try to size the TextBlock to fit your expected text exactly, but that gets ugly fast trying to account for varying input or different font sizes.

Instead, you can verify the character length of the string to be assigned to the TextBlock.Text property and limit it if necessary.

string s = "new text";
if (s.Length > maxLen)
    textBlock1.Text = s.Substring(0, maxLen);
else
    textBlock1.Text = s;

Another option is to use the TextWrapping and TextTrimming properties. The following attributes could be added to your TextBlock xaml to add line wrapping and "..." to denote that text exists beyond the size of the TextBlock.

<TextBlock ... TextWrapping="Wrap" TextTrimming="CharacterEllipsis" />
Adam S
  • 3,065
  • 1
  • 37
  • 45
5

You can use 'TextTrimming' Property of a Textblock. Set TextTrimming = "CharacterEllipsis". You might need to play with Width to manage how many characters you really want to display.

<TextBlock TextTrimming="CharacterEllipsis" Text="{Binding Subject}"/>
zamoldar
  • 548
  • 10
  • 13
1

Either Set MaxHeight = "SomeHeight" and trim the overflow with

<TextBlock TextTrimming="CharacterEllipsis" Text="{Binding LongText}"

Or Use TextBox like Textblock by setting

<TextBox IsReadOnly="True" Background="Transparent" BorderThickness="0"
 MaxLength="100"
Abdul Saleem
  • 10,098
  • 5
  • 45
  • 45