foreyez foreyez - 3 months ago 19
C# Question

How to know if text is bigger than textbox?

Is there a way to know if my text within a wpf textbox has exceeded the length of it?

** NOTE: I'M TALKING ABOUT PIXEL LENGTH NOT CHARACTER LENGTH OF MAXLENGTH

So basically, if the textbox is 50 pixels long.
And I have a text in it that is:
"Supercalifragilisticexpialidocious! Even though the sound of it is something quite atrosicous"

Then it won't fit in there right? I'd like to KNOW that it didn't fit in it.
But if the textbox is 900 pixels wide. It just might.

I'm currently checking with something like the following.

private double GetWidthOfText()
{
FormattedText formattedText = new FormattedText(MyTextbox.Text,
System.Globalization.CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight, new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), MyTextbox.FontSize, Brushes.Black);
return formattedText.Width;
}


...

if (textBox.Width < GetWidthOfText()) ...


But I find it to be incredibly hacky and never really works. I'm trying to find something more reliable. Any ideas?

Answer

You could inherit from the textbox and then create a custom method to return the value you want:

public class MyTextBox :TextBox 
{
    public bool ContentsBiggerThanTextBox()
    {
        Typeface typeface = new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, this.FontStretch);
        FormattedText ft = new FormattedText(this.Text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, this.FontSize, Brushes.Black);
        if (ft.Width > this.ActualWidth)
            return true;

        return false;
    }
}

You declare the textbox in the XAML as a MyTextBox instead of TextBox, then you can simply do:

private void button1_Click(object sender, RoutedEventArgs e)
{
    if (tb.ContentsBiggerThanTextBox())
        MessageBox.Show("The contents are bigger than the box");
}