ModelValidation with separate model class #336
-
ModelValidation does not work with the property of the object being validated. For example, there is a ViewModel: public sealed class PublicationViewModel : Screen
{
public Publication? Result { get; private set; }
public string? Title { get; private set; }
public bool CanAccept => !HasErrors;
public PublicationViewModel()
{
Result = new()
{
Address = new(),
Subscription = new()
};
Validator = new FluentValidationAdapter<PublicationViewModel>(new PublicationViewModelValidator());
Validate();
}
public void Accept()
{
if (Validate())
RequestClose(true);
}
protected override void OnValidationStateChanged(IEnumerable<string> changedProperties)
{
base.OnValidationStateChanged(changedProperties);
NotifyOfPropertyChange(() => CanAccept);
}
} Validator for it: public sealed class PublicationViewModelValidator : AbstractValidator<PublicationViewModel>
{
public PublicationViewModelValidator()
{
RuleFor(model => model.Result).SetValidator(new PublicationValidator());
}
} Validator for Publication model: public sealed class PublicationValidator : AbstractValidator<Publication>
{
public PublicationValidator()
{
RuleFor(model => model.Title).Length(4).WithMessage("Test message");
}
} In example with validation, the validated properties are directly inside the ViewModel, but if you put them in a separate class, the validation does not work. Is this a proper behavior? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
It's to be expected. It's exactly the same problem as if you bind to properties of an object where that object does not implement INPC. Validation works through The parent object of your This is just another application of the general WPF rule, which is "Do not bind to things which are not ViewModels" |
Beta Was this translation helpful? Give feedback.
It's to be expected. It's exactly the same problem as if you bind to properties of an object where that object does not implement INPC.
Validation works through
INotifyDataErrorInfo
. When you bind to a property, WPF checks to see whether the parent object implements that interface, and if it does, it subscribes to validation events.The parent object of your
Title
property is thePublication
class. So that's the class which needs to implementINotifyDataErrorInfo
(usually, with Stylet, by subclassingValidatingModelBase
).This is just another application of the general WPF rule, which is "Do not bind to things which are not ViewModels"