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.