Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if text is bigger than textbox?

Tags:

c#

wpf

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?

like image 740
Shai UI Avatar asked Jun 05 '12 16:06

Shai UI


2 Answers

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");
}
like image 136
John Koerner Avatar answered Oct 20 '22 02:10

John Koerner


if (textBox.ExtentWidth > textBox.ActualWidth)
{
    // your textbox is overflowed
}

Works with .NET 4.5.2

like image 4
HaveSpacesuit Avatar answered Oct 20 '22 02:10

HaveSpacesuit