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!
Asked
Active
Viewed 9,846 times
1
-
1You need to write your own validation for that. http://stackoverflow.com/a/43029089/424129 – 15ee8f99-57ff-4f92-890c-b56153 Apr 03 '17 at 14:31
-
There is no min. Please elaborate, what are you trying to do – Gilad Apr 03 '17 at 14:34
-
I want to limit my texbox to only 10 character length. not more. not fewer. only 10. – Reza.S Apr 03 '17 at 14:41
-
`MaxLength` sets the visual length of the control, it has nothing to do with character count. You need to implement your own validation for the control, as Ed Plunkett suggested. – mechanic Apr 03 '17 at 14:48
-
I think "Ed Plunkett" answered good. But I don't know regex's code for min length. – Reza.S Apr 03 '17 at 14:58
3 Answers
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:

Federico Navarrete
- 3,069
- 5
- 41
- 76
-
2You have written the same answer as that of mine. What's different in this? – Parag Apr 03 '17 at 15:27
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