WPF如何限制多行TextBox中的最大行数

时间:2015-12-16 03:47:53

标签: wpf xaml textbox

我想将多线TextBox中允许的行数限制为3.我尝试使用MaxLines,但这并没有解决我的问题。

我试过这样做:

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

但是,我仍然可以按Enter键并添加3行以上的文字。

4 个答案:

答案 0 :(得分:0)

我认为您必须使用LineHeight,MaxHeight and TextTrimming进行设置。以下代码适用于3行

<TextBlock 
  Width="300"
  TextWrapping="Wrap" 
  TextTrimming="WordEllipsis" 
  FontSize="24" 
  LineStackingStrategy="BlockLineHeight"
  LineHeight="28"
  MaxHeight="84">YOUR TEXT</TextBlock>

答案 1 :(得分:0)

这对我有用

    <TextBox 
  Text="Initial text in TextBox" 
  Width="200" 
  AcceptsReturn="True"
  TextAlignment="Center"
  TextWrapping="Wrap" 
  MaxLength="500"
  MinLines="1" 
  MaxLines="3" />

答案 2 :(得分:0)

关于此主题的文章很多,所有这些文章都倾向于使用XAML的MaxLines。但是他们还指出,这仅限制了视图中的行数,而不是文本的实际行数-滚动查看器通常会出现,以便查看其他行。虽然您可以使用MaxLength限制字符数,但是这不计算行数。我发现以下代码是答案-遍历文本,删除所有多余的文本,直到文本框为或保持正确的大小。它还处理用户将文本粘贴到创建过多行的文本框中。希望对您有所帮助。

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
            }
        }
    }

这会去除单个字母,因此会留下部分单词。您还可以在用户键入每个字符时(带有KeyDown)或之前(带有PreviewKeyDown)测试多余的行,并以这种方式捕获任何多余的字符。

答案 3 :(得分:-2)

JQuery解决方案检查新的行密钥,如果当前行计数与文本框最大行匹配,则不插入新行

function limitTextareaLine(e) {
if(e.keyCode == 13 && $(this).val().split("\n").length >= $(this).attr('rows')) { 
    return false;
}

}

Limiting number of lines in textarea

相关问题