WPF RichTextBox automatically adjusts the height

Source: Internet
Author: User

During this period about two years ago, the project encountered a problem: VS2005 and WinForm, and RichTextBox was required to automatically adjust the height according to the content. At that time, I failed to solve the problem by using various methods. I tried this function several times later. This feature has become a heart disease for me.

This section uses Silverlight, then learns WPF, and tries to use RichTextBox in WPF to implement this function. It was not really implemented before, and it was not very complicated.

A custom control inherits System. Windows. Controls. RichTextBox.

Key code:

 1         private void AdjustHeight()
2 {
3 Rect rectStart = Document.ContentStart.GetCharacterRect(LogicalDirection.Forward);
4 Rect rectEnd = Document.ContentEnd.GetCharacterRect(LogicalDirection.Forward);
5 var height = rectEnd.Bottom - rectStart.Top;
6 var remainH = rectEnd.Height / 2.0;
7 var myHeight = Math.Min(MaxHeight, Math.Max(MinHeight, height + remainH));
8
9 if (myHeight > BaseHeight)
10 {
11 this.Height = myHeight;
12 }
13 }

The key point is that the first and last word positions can be obtained in RichTextBox.

 

Get the content in WPF:

String ss = new TextRange (rtbENotes. Document. ContentStart, rtb. Document. ContentEnd). Text;

This. rtb. Document = new FlowDocument (new Paragraph (new Run (sss )));

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.