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 )));