1

I want to set "Min Length" property for My TextBox in C# - WPF. In fact I have a TextBox in my window and I want to limit it to only 10 character. I set max length to 10 but I don't find min length property!

Sosian
  • 622
  • 11
  • 28
Reza.S
  • 25
  • 1
  • 5

3 Answers3

1

Create one property "MinLength" in your view model.

Attach a lost focus event handler to your textbox and inside it, put the check for minimum number of characters using above declared property. If textbox length is <10, then again set focus in same textbox.

Xaml:

<TextBox LostFocus="UIElement_OnLostFocus"></TextBox>

Code behind:

private void UIElement_OnLostFocus(object sender, RoutedEventArgs e)
    {
        // check condition here
    }
Parag
  • 543
  • 1
  • 8
  • 18
0

I will suggest you something like this:

On the event Lost Focus, you handle when the user left the TextBox:

XAML:

<TextBox LostFocus="TextBox_LostFocus" />

Later with the Length property you set the minimum of characters that you expect.

C#:

private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    if (((TextBox)sender).Text.Length < 5)
    {
        MessageBox.Show("You need to write at least 5 characters");
    }
}

This is how it should look:

example

Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76
0

Have had the same problem and solved it this way ... Maybe it's not a nice programming style!? :)

int (name) = 0;
(name) = (textbox).TextLength;

if((name) >= (min input you like){
(do something)}

else {ErrorMessage)}
Thomas
  • 5
  • 4