3

Users of my application can enter values into TextBoxes. In some cases the values need to be restricted to a certain range, e.g. 0 to 1, or 1 to 50. In other cases they can only enter upto 13 or 20 characters depending.

Can I use Binding.StringFormat to enforce these ranges? If so,

  • what do I need to specify to restrict values to a certain character length?
  • what do I need to specify to restrict values to a certain range?

If not, what's the best way to implement this?

DaveDev
  • 41,155
  • 72
  • 223
  • 385

4 Answers4

3

What you want is input validation. For starters this tutorial on MSDN will help you, more information on IDataErrorInfo (preferred way) can be obtained here.

This question was already a topic on SO: WPF Data Binding and Validation Rules Best Practices

Community
  • 1
  • 1
Matten
  • 17,365
  • 2
  • 42
  • 64
  • That sounds like something completely different - IMO there is difference between notifying input is not valid and disallowing invalid input. – wondra Jan 14 '20 at 10:11
1

The Vaildation in WPF Code Project should give you a good start.

Also the related question WPF Validators like ASP.NET should assist.

Community
  • 1
  • 1
Joshua Drake
  • 2,704
  • 3
  • 35
  • 54
  • I agree with Joshua Drake. Use Validation. I have an example of how to do the Validation for you. http://www.wpfsharp.com/2012/02/03/how-to-disable-a-button-on-textbox-validationerrors-in-wpf/ – Rhyous Apr 13 '12 at 15:33
1

You need to use Input mask, Check out this article WPF Maskable TextBox for Numeric Values

Based on this article in Events TextBox_PreviewTextInput and TextBoxPastingEventHandler you could check for a range.

Habib
  • 219,104
  • 29
  • 407
  • 436
-1

The text box length property should solve

Textbox.maxlength= 10;
rahul
  • 7,573
  • 7
  • 39
  • 53
Kiran
  • 47
  • 1