Data Validation
最后更新于
这有帮助吗?
最后更新于
这有帮助吗?
Avalonia offers different data validation options. In this section we will show you how you can validate the Properties
of your ViewModel
and how you can style the displayed error message.
Avalonia uses to validate the Properties
you bound to. Out of the box Avalonia provide these three validation plugins:
You can decorate the Properties
of your ViewModel
with different . You can use the build-in ones, use the or create your own by derive from ValidationAttribute
.
Sample: The property EMail is required and must be a valid e-mail-address
Sample: Validate the property EMail using Exceptions
Exceptions inside the getter of your property are not allowed and will result in a crash of your application.
Example Style for DataValidationErrors
Custom validation style
Example: Remove the DataAnnotations validator
Avalonia also supports validation of classes that implement . Several MVVM
-libraries are using this interface for their data validation, for example the -package and the -package. For usage instructions please visit the documentation of the MVVM
-package of your choice.
Some libraries like the Microsoft.Toolkit.Mvvm
use DataAnnotiations
for their validation. This may result in conflicts with the . Please see how to solve this issue.
One more option to validate a property is to raise an inside the setter of your property.
To display the validation messages, Avalonia has a control called . This control is typically placed inside the ControlTemplate
of all Controls
that supports data validation, like TextBox
, Slider
and other. You can create your own Style
of the DataValidationErrors
-control in order to customize the representation of the error messages.
if needed to, you can enable or disable a specific in your App. This can be useful if for example your MVVM-framework uses DataAnnotations
to validate the property via INotifyDataErrorInfo
. In that case you would see the message twice. Use the -collection to add or remove a specific ValidationPlugin
.