I've got a few TextBoxes for input fields and a "Save" Button in my view. Two of the TextBoxes are required fields for saving, and I've set up a custom ValidationRule in the xaml for some visual feedback (red borders and tooltips) like so:
<TextBox ToolTip="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}">
<TextBox.Text>
<Binding Path="ScriptFileMap" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<v:MinimumStringLengthRule MinimumLength="1" ErrorMessage="Map is required for saving." />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
The "Save" Button is linked to a DelegateCommand which calls the SaveScript() function. The function doesn't allow the user to save if the properties of the two required fields are empty:
public void SaveScript()
{
if (this.ScriptFileName.Length > 0 && this.ScriptFileMap.Length > 0)
{
// save function logic
}
}
However, the function still allows the file to be saved. On closer inspection, I see that the values of those two fields (ScriptFileName and ScriptFileMap) are not being updated when the ValidationRule fails, and it goes by the last known value.
Is this the expected behavior for ValidationRule or do I have something missing or a glitch somewhere? If the former, is there a way to override that behavior? I can't prevent the saving in the ViewModel if the empty string is never passed into the bound property.
Yes, that is the expected behavior. By default, validation rules run on the raw proposed value, i.e., the value before it gets converted and written back to the binding source.
Try changing the ValidationStep
on your rule to UpdatedValue
. That should force the rule to run after the new value is converted and written back.
You should implement CanExecute
method and RaiseCanExecuteChanged
event which will keep your button disabled until all the required properties pass the validation logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With