Shai UI
Shai UI

Reputation: 51918

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?

Upvotes: 7

Views: 7185

Answers (5)

HaveSpacesuit
HaveSpacesuit

Reputation: 3994

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

Works with .NET 4.5.2

Upvotes: 4

AnjumSKhan
AnjumSKhan

Reputation: 9827

Best would be to use a hidden TextBlock and bind it's MinWidth and Text property to the corresponding TextBox. Keep this TextBlock as hidden. When Text surpasses the bounds, the width of hidden textblock will increase as it is having its MinWidth set and not Width. In it's SizeChanged event we check and compare ActualWidth of TextBlock and TextBox. If ActualWidth of TextBlock is more than that of TextBox, this means that text is large.

I have checked this approach with multiple font sizes and works good.

<TextBox x:Name="textBox" Width="120" AcceptsReturn="False" TextWrapping="NoWrap" />
<TextBlock x:Name="tblk" TextWrapping="NoWrap" Text="{Binding Text, ElementName=textBox}" MinWidth="{Binding Width, ElementName=textBox}" Visibility="Hidden" SizeChanged="TextBlock_SizeChanged" />

code-behind :

private void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //if (e.NewSize.Width > tblk.MinWidth)
            if(tblk.ActualWidth > textBox.ActualWidth)
                tbStatus.Text = "passed";
            else
                tbStatus.Text = "";
        }

Upvotes: 0

CatGuardian
CatGuardian

Reputation: 321

John Koemer's answer doesn't work if you are not targeting the .NET 4.5 or later framework.

Use this method if you are targeting the .NET 4.0 framework like I am:

    private bool IsContentsBiggerThanTextBox(TextBox textBox)
    {
        Size size = TextRenderer.MeasureText(textBox.Text, textBox.Font);
        return ((size.Width > textBox.Width) || (size.Height > textBox.Height));
    }

This also works for multi-line textboxes. So if you have more lines than the textbox can display this method also works.

Note that this was actually done in a Windows Forms Application and not a WPF application so I don't guarantee it will work on the WPF side.

Upvotes: 2

John Koerner
John Koerner

Reputation: 38077

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");
}

Upvotes: 7

Limey
Limey

Reputation: 2772

This should do it.

        int tblength = txtMytextbox.MaxLength;
        string myString = "My text";
        if (myString.Length > tblength)

I did this in a web form, but since its all on the back end, I assume it should be the same for a winform.

Upvotes: -1

Related Questions