2

I would like to limit number of lines allowed in my multiline TextBox to 3. I have tried using MaxLines but that did not resolve my issue.

I tried doing this:

<TextBox TextWrapping="Wrap" AcceptsReturn="True" MaxLines="3"/>

However, I can still hit Enter key and add more than 3 lines of text.

Vijay Chavda
  • 826
  • 2
  • 15
  • 34
pixel
  • 9,653
  • 16
  • 82
  • 149

3 Answers3

0

This worked for me

    <TextBox 
  Text="Initial text in TextBox" 
  Width="200" 
  AcceptsReturn="True"
  TextAlignment="Center"
  TextWrapping="Wrap" 
  MaxLength="500"
  MinLines="1" 
  MaxLines="3" />
Justin CI
  • 2,693
  • 1
  • 16
  • 34
0

There have been a number of posts on this subject, all of which tend to use XAML's MaxLines. But they also point out that this just limits the number of lines in view, not the actual number of lines of text - a scrollviewer will generally appear for additional lines to be viewed. While you can limit the amount of characters using MaxLength, this does not count lines. I found the following code to be the answer - it iterates through the text removing any surplus text until the textbox is, or remains, the right size. It also deals with a user pasting text into the text box that creates too many lines. Hope it is helpful.

private void TbxInvestmentNotes_LostFocus(object sender, RoutedEventArgs e)
    {
        int lineHeight = 20;//or whatever line height your text uses, in pixels
        int desiredLines = 20;
        if (TbxInvestmentNotes.ActualHeight>desiredLines*lineHeight) 
        {
            MessageBox.Show(string.Format("Your notes may not exceed {0} lines.  \n\nYour text has therefore been truncated to fit the available space."
                , desiredLines), "Notes too long", MessageBoxButton.OK, MessageBoxImage.Stop);
            while (TbxInvestmentNotes.ActualHeight> desiredLines * lineHeight)
            {
                TbxInvestmentNotes.Text = TbxInvestmentNotes.Text.Remove(TbxInvestmentNotes.Text.Length - 1);
                TbxInvestmentNotes.UpdateLayout();//Necessary, to reset value of ActualHeight after each iteration
            }
        }
    }

This strips individual letters so will leave partial words. You could also test for excessive lines when (with KeyDown) or before (with PreviewKeyDown) each character is typed by a user and capture any excess characters that way.

MikeW
  • 47
  • 6
0

Add PreviewKeyDown event to TextBox like this:

 private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (TextBox.LineCount >= 3 && e.Key == Key.Enter)
            {                                 
                e.Handled = true;               
            }
        }
Tippi
  • 15
  • 4