Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Get rid of the OnClick event handler, instead use a binding to a command.<BR/> Register the command in the VM with a CanExecute method that returns Model.IsValid.</p> <p>If the validation failure is in the binding of the view to the viewmodel, then the viewmodel can still be valid - since it didn't store the update (due to type mismatch, range check, etc).</p> <p>In this case consider storing error state in VM, before throwing exception, then clearing error state if same property was successfully set.</p> <p>Modified code:</p> <p><HR/> XAML:<BR/> <I>(Note that the scope of ValidationRules:NameRule instance is in TextBox, other usages will receive another instance with different field values)</I></p> <pre><code>&lt;TextBox Width="250" Height="25" Margin="5" Validation.ErrorTemplate="{StaticResource customErrorTemplate}"&gt; &lt;TextBox.Text&gt; &lt;Binding Path="WitnessName" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"&gt; &lt;Binding.ValidationRules&gt; &lt;ValidationRules:NameRule x:Name="nameValidator" /&gt; &lt;/Binding.ValidationRules&gt; &lt;/Binding&gt; &lt;/TextBox.Text&gt; &lt;/TextBox&gt; </code></pre> <p><HR/> Validation rule:</p> <pre><code>public class NameRule : ValidationRule, INotifyPropertyChanged { public bool HasFailed // set default of field behind to false { get; // change to support INotifyPropertyChanged set; // change to support INotifyPropertyChanged } public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { var isValid = (value as string == null) || Regex.IsMatch(value.ToString(), @"^[\p{L} \.'\-]+$"); HasFailed = !isValid; return new ValidationResult(isValid, "Name can contain only letters, apostrophes and hyphens."); } } </code></pre> <p><HR/> Command:</p> <pre><code>public bool CanExecute(object parameter) { return this.witnessDialogue.IsValid &amp;&amp; !this.witnessDialogue.nameValidator.HasFailed; } public void Execute(object parameter) { this.witnessDialogue.OnOkClick(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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