Hi,
in your code you validate in 2 levels: UI and data object (in your case in ViewModel). Validation in UI level your code don't inform ViewModel. If you want inform ViewModel you can:
Set Validation.Error and NotifyOnValidationError="True"
<Label>Interval</Label>
<TextBox x:Name="TimeRecordInterval" Validation.Error="Validation_Error"
Grid.Row="0"
Grid.Column="1">
<TextBox.Text>
<Binding Path="TimeRecordInterval" NotifyOnValidationError="True"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<viewmodels:NumberValidationRule numberValidation="number" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
...
Include Event method:
using SimpleValidator.ViewModels;
using System.Windows;
using System.Windows.Controls;
namespace SimpleValidator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ViewModel ViewModel { get; set; }
public MainWindow()
{
ViewModel = new ViewModel();
DataContext = ViewModel;
InitializeComponent();
}
private void Validation_Error(object sender, System.Windows.Controls.ValidationErrorEventArgs e)
{
string name = ((TextBox)sender)?.Name;
ViewModel.SetTimeRecordInterval(name, e);
}
}
}
and in ViewModel:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace SimpleValidator.ViewModels
{
public class ViewModel : BaseViewModel, INotifyDataErrorInfo
{
private readonly PropertyErrors errors;
public ICommand SaveCommand => new RelayCommand(param => this.SaveSettings(),
(obj) => !this.HasErrors && this.UiErrorMessages.Count==0);
private readonly Dictionary<string, string> UiErrorMessages = new Dictionary<string, string>();
public void SetTimeRecordInterval(string ctrlName, ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Added) this.UiErrorMessages[ctrlName] = e.Error.ErrorContent.ToString();
if (e.Action == ValidationErrorEventAction.Removed) this.UiErrorMessages.Remove(ctrlName);
OnPropertyChanged(nameof(SaveCommand));
}
private void SaveSettings()
{
if (!HasErrors && UiErrorMessages.Count == 0)
MessageBox.Show("Save");
}