I am trying to implement UI Validation using ObservableValidator from the CommunityToolkit to highlight controls and show error messages when they appear. From the docs I could only find on how to implement the required attributes for the ViewModel, not the Xaml part itself, so I suppose it should work out of the box. I have broken down the problem to a simple reproducable project, here is some code (this is of course only to reduce as much overhead as possible, and only an example to showcase my problem):
View code (MainWindow.xaml):
<Grid x:Name="root">
<TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="70" Width="150"/>
</Grid>
Code behind (MainWindow.xaml.cs):
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
root.DataContext = new ViewModel();
}
}
public partial class ViewModel : ObservableValidator
{
[ObservableProperty]
[NotifyDataErrorInfo]
[Required(ErrorMessage = "Username cannot be empty.")]
[MinLength(2, ErrorMessage = "Provide more than 1 Character.")]
private string _name;
}
This is pretty much as simple as it gets. What am I missing, is the behavior I want really not supported or am I misunderstanding something? Help is much appreciated.
You need to subscribe to ErrorsChanged
:
public ViewModel()
{
this.ErrorsChanged += ViewModel_ErrorsChanged;
}
private void ViewModel_ErrorsChanged(object? sender, DataErrorsChangedEventArgs e)
{
if (this.HasError is true)
{
}
}
You should check out the MVVM Toolkit Sample App. It has some sample code with a custom control ValidationTextBox which handles error messages by itself.
The sample code in the MVVM Toolkit Sample App is
ValidationFormWidgetViewModel
.