doull
doull

Reputation: 21

wpf,how to restrict MaxLength of TextBox?

<TextBox Height="?" Width="?" AcceptReturn="true" />

Height=Random; Width=Random; For example,Height is 60, Width is 100. How to control inputed lentgh of text less than size of TextBox

Upvotes: 2

Views: 6809

Answers (2)

VVS
VVS

Reputation: 19604

Use MaxLength

EDIT:

Wait, what? You want to restrict the number of chars to the width of the TextBox? Why that?

EDIT2:

You can measure the length of a string by using Graphics.MeasureString. Here's an extension method that does what you want:

public static class TextBoxExtension
{
    public static int VisibleCharCount(this textBox textBox)
    {
        int count = 0;

        do {
            count++;
            var testString = new string('X', count);
            var stringWidth = System.Drawing.Graphics.MeasureString(testString, textBox.Font);                
        } while (stringWidth < textBox.Width);

        if (stringWidth == textBox.Width) 
            return count;
        else
            return count-1;
    }
}

Use it like this:

myTextBox.MaxLength = myTextBox.VisibleCharCount();

EDIT3:

If your TexBox is MultiLine and you also want to take the height into account, you can use the overload of MeasureString that takes a Size. I leave it up to you to modify my example accordingly.

Upvotes: 6

Arcturus
Arcturus

Reputation: 27055

Use the MaxLength property on TextBox, which can be quite static once initialized.

OR

You can cancel the text input with the PreviewTextInput event:

textbox.PreviewTextInput += textbox_PreviewTextInput;

void textbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
   TextBox box = (TextBox) sender;
   e.Handled = box.Text.Length > 5;
}

Upvotes: 0

Related Questions