Setting WPF RichTextBox width and height according to the size of a monospace font

Posted by oxeb on Stack Overflow See other posts from Stack Overflow or by oxeb
Published on 2010-04-02T21:02:00Z Indexed on 2010/04/02 21:03 UTC
Read the original article Hit count: 532

Filed under:
|
|
|

I am trying to fit a WPF RichTextBox to exactly accommodate a grid of characters in a particular monospace font. I am currently using FormattedText to determine the width and height of my RichTextBox, but the measurements it is providing me with are too small--specifically two characters in width too small.

Is there a better way to perform this task? This does not seem to be an appropriate way to determine the size of my control.

RichTextBox rtb;
rtb = new RichTextBox();
FontFamily fontFamily = new FontFamily("Consolas");
double fontSize = 16;
char standardizationCharacter = 'X';
String standardizationLine = "";
for(long loop = 0; loop < columns; loop ++) {
    standardizationLine += standardizationCharacter;
}
standardizationLine += Environment.NewLine;
String standardizationString = "";
for(long loop = 0; loop < rows; loop ++) {
    standardizationString += standardizationLine;
}
Typeface typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
FormattedText formattedText = new FormattedText(standardizationString, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, fontSize, Brushes.Black);
rtb.Width = formattedText.Width;
rtb.Height = formattedText.Height;

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf