Visible line count of a TextBlock

前端 未结 4 1121
Happy的楠姐
Happy的楠姐 2020-12-16 02:44

If you set TextWrapping to \"Wrap\", a WPF TextBlock can have several lines of text. Is there a \"clean\" way to get the number of lines of text? I considered looking at the

4条回答
  •  难免孤独
    2020-12-16 03:15

    // this seems to do the job        
    
    
    
    
    
            /// 
            /// we need to limit a multi line textbox at entry time
            /// 
            /// 
            /// The sender.
            /// 
            /// 
            /// The e.
            /// 
            private void DescriptionTextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
            {
                TextBox thisTextBox = sender as TextBox;
                if (thisTextBox != null)
                {
                    // only check if we have passed the MaxLines 
                    if (thisTextBox.LineCount > thisTextBox.MaxLines)
                    {
                        // we are going to discard the last entered character
                        int numChars = thisTextBox.Text.Length;
    
                        // force the issue
                        thisTextBox.Text = thisTextBox.Text.Substring(0, numChars - 1);
    
                        // set the cursor back to the last allowable character
                        thisTextBox.SelectionStart = numChars - 1;
    
                        // disallow the key being passed in
                        e.Handled = true;
                    }
                }
            }
    

提交回复
热议问题