I am trying to get WPF validation to work in the MVVM pattern.
In my view, I can check for a TextBox like this, which is handled by the "HandleError" code method, which works fine:
<TextBox Width="200" Validation.Error="HandleError"> <TextBox.Text> <Binding Path="FirstName" NotifyOnValidationError="True" Mode="TwoWay"> <Binding.ValidationRules> <validators:DataTypeLineIsValid/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox>
However, I would like to handle validation in my ViewModel using DelegateCommand, but when I try it with the following code, I get an explicit error " '{Binding HandleErrorCommand}' is not a valid name event handler method. Only valid class methods the generated code or code is valid. "
Is there any workaround for this so that we can handle validations in the MVVM pattern?
View:
<TextBox Width="200" Validation.Error="{Binding HandleErrorCommand}"> <TextBox.Text> <Binding Path="FirstName" NotifyOnValidationError="True" Mode="TwoWay"> <Binding.ValidationRules> <validators:DataTypeLineIsValid/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox>
ViewModel:
#region DelegateCommand: HandleError private DelegateCommand handleErrorCommand; public ICommand HandleErrorCommand { get { if (handleErrorCommand == null) { handleErrorCommand = new DelegateCommand(HandleError, CanHandleError); } return handleErrorCommand; } } private void HandleError() { MessageBox.Show("in view model"); } private bool CanHandleError() { return true; }
c # validation wpf mvvm
Edward tanguay
source share