Tuesday, February 19, 2008

WPF Limit number of lines in multi line TextBox

WPF TextBox controls do not have a property to limit the number of lines of text that can be entered into a control. Here is a bit of C# to provide the functionality

XAML

<TextBox Height="138" Name="textBox_DeliverFrom" Width="257" AcceptsReturn="True" PreviewKeyDown="textBox_DeliverFrom_PreviewKeyDown" />


C#

private void textBox_DeliverFrom_PreviewKeyDown (object sender, KeyEventArgs e)
{
// Do not allow more than 8 Lines
if (e.Key == Key.Enter)
{
if (textBox_DeliverFrom.LineCount > 7)
e.Handled = true;
}
}

One needs to add a PreviewKeyDown handler and ignore then Enter key if the control has reached the required limit.

1 comment:

redsolo said...

Thanks! You saved me a few hours :)