Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to validate data in WPF and set default value?
    text
    copied!<p>I'm trying to perform a validation property. We have a nullable property called:</p> <pre><code> public int? Number { get { return _number; } set { if (_number != value) { _number = value; RaisePropertyChanged("Number"); } } } </code></pre> <p>And this property is bound to a textbox. I only want to validate this two escenarios:</p> <ul> <li>Imagine that the user left the textbox empty (textbox.text=""), so Number property must receive null value (instead "" ).</li> <li>And if the user inputs "2b", Number property must have a null value (because is an error), but the textbox must still say "2b".</li> </ul> <p>I guess IDataNotifyError and ValidationRules is not working for this. How can I resolve these situations?</p> <p>EDIT: I'm using also a ValidationRule to show a custom message when the user inputs an incorrect format. But when this happens, does not fire the property to null. And if a put true in that error, it fired, but does not show any error message.</p> <pre><code> &lt;TextBox.Text&gt; &lt;Binding Path="Number" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" ValidatesOnExceptions="True" NotifyOnValidationError="True" Converter="{x:Static c:IntConverter.Default}" &gt; &lt;Binding.ValidationRules&gt; &lt;r:NumericValidation /&gt; &lt;/Binding.ValidationRules&gt; &lt;/Binding&gt; &lt;/TextBox.Text&gt; </code></pre> <p>The validation rule</p> <pre><code>public class NumericValidation : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { int? response; bool noIllegalChars = TryParseStruct&lt;int&gt;(value.ToString(), out response); if (noIllegalChars == false) { return new ValidationResult(false, "Input is not in a correct format."); } else { return new ValidationResult(true, null); } } ... } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload