foreyez foreyez - 1 year ago 117
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?


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,
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 Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download