I am working in wpf mvvm app, and I also use Community toolkit.mvvm also. Here I implement Observable validator for textboxes but it does not effect on user interface,
ViewModel:
public partial class UserViewModel : ObservableValidator
{
[ObservableProperty]
[Required(ErrorMessage ="Name is Required")]
[MinLength(3)]
private string name= "";
}
Xaml:
<TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
When I type on textbox less than 3 character and leave it It does not effect, The TextBox accept characters in every range and also accept empty.
After Edited: Thank You! Mr. @mm8
I just change my ViewModel property like this, I think I have missed third parameter of SetProperty which is 'true', Now its working. I see the red border while its invalid, But i don't see the error message.
ViewModel:
public partial class UserViewModel : ObservableValidator
{
private string username;
[Required(ErrorMessage ="Name is Required")]
[MinLength(3, ErrorMessage ="Name Should be at least 3 character")]
public string Username
{
get => username;
set => SetProperty(ref username, value, true);
}
}
Xaml:
<TextBox Text="{Binding Username, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
I have add ValidatesOnDataErrors=True, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True to xaml but I could not see the error message.
CodePudding user response:
Confirm that the binding is working. Setting the ValidatesOnDataErrors
property of the binding to true
shouldn't be necessary:
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"/>