0

I'm trying to bind a property value to a TextBox.

The property is of type int, and the user can type any text they want.

If the user were to type in a non-numeric value, I can see an exception is thrown in the Output window. This makes sense.

I've added a new control, which inherits from ValidationRule and I call that instead (which removes the exception). However, it doesn't really help as I don't think I can change the value (the value the user entered).

What I'd like to do within the ValidationRule is take the bogus value the user entered and remove non valid characters. EG, if they enter 3d I'd like the d to be automatically removed. The issue I have is that the signature clearly only returns a ValidationResult

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)

Also, is there a way to know which property is being validated. When the code is in the Validate function (shown above), I'd like to know which property is being validated!

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • You could change the text in the TextBox's `LostFocus` event. You don't want to change it in `TextChanged`, because that'll be changing it while the user is typing and that's exceedingly hard to make usable. Another approach is the "masked text box" approach: Handle `KeyDown` and simply refuse to accept any characters other than 0 through 9. – 15ee8f99-57ff-4f92-890c-b56153 Sep 08 '16 at 13:42
  • 1
    I think you should handle it at the TextBox, not in the validation. That is, don't let the TextBox ever take invalid characters. See http://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf – J.H. Sep 08 '16 at 13:43
  • Even that post does suggest the [validationrule](http://stackoverflow.com/a/1268575/3252861) – MyDaftQuestions Sep 08 '16 at 14:15

0 Answers0