Justin
Justin

Reputation: 2479

Wpf- How can I get the LineHeight of a normal TextBox in code?

I'm working on a CustomControl that inherits from TextBox and can be re-sized by holding Ctrlwhile dragging the mouse, but sometimes when you re-size it, lines get cut off like this:

enter image description here

If this happens, I would like to adjust the chosen height, so that lines are not cut off. This is the code I have so far:

double LineHeight = ??;
double requiredHeightAdjustment = this.Height % LineHeight; 

                if (requiredHeightAdjustment != 0)
                {
                    this.Height -= requiredHeightAdjustment;
                }

--Edit--

In case anyone needs this in the future here is what I ended up with:

double fontHeight = this.FontSize * this.FontFamily.LineSpacing;

double requiredHeightAdjustment = this.Height % fontHeight;

var parent = this.Parent as FrameworkElement;

if (requiredHeightAdjustment != 0)
{
    double upwardAdjustedHeight = (fontHeight - requiredHeightAdjustment) + this.Height;

    if (requiredHeightAdjustment >= fontHeight / 2 && this.MaxHeight >= upwardAdjustedHeight
        && (parent == null || parent.ActualHeight >= upwardAdjustedHeight))
        this.Height = upwardAdjustedHeight;
    else
        this.Height -= requiredHeightAdjustment;
}

This solution also makes the smallest necessary change to the chosen TextBox size instead of always making a negative change.

Upvotes: 6

Views: 7275

Answers (2)

Philipp Schmid
Philipp Schmid

Reputation: 5828

Since your LineHeight is dependent on the font family and font size, you might want to look at the GlyphTypeface class in .NET 3.0+. It might be a bit too low-level though, but it has properties like Height.

Upvotes: 3

dotNET
dotNET

Reputation: 35400

This has been asked several years ago, but just in case anyone lands here searching for a solution, you can use TextBlock.LineHeight attached property to get TextBox's LineHeight:

var LH = TextBlock.GetLineHeight(YOUR_TEXTBOX);

Upvotes: 0

Related Questions