【问题标题】:WPF How to limit max number of lines in a multiline TextBoxWPF如何限制多行文本框中的最大行数
【发布时间】:2015-12-16 03:47:52
【问题描述】:

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

我试过这样做:

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

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

【问题讨论】:

    标签: wpf xaml textbox


    【解决方案1】:

    这对我有用

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

    【讨论】:

      【解决方案2】:

      已经有很多关于这个主题的帖子,所有这些帖子都倾向于使用 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】:

        像这样将 PreviewKeyDown 事件添加到 TextBox:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-23
          • 1970-01-01
          • 2016-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-08
          相关资源
          最近更新 更多