Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

textbox

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.

like image 707
Justin Avatar asked Nov 04 '22 20:11

Justin


1 Answers

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.

like image 71
Philipp Schmid Avatar answered Nov 14 '22 23:11

Philipp Schmid