I have a registration form with few fields. It´s a PRISM MVVM application.
XAML of one of the field looks like this (RegisterView.xaml):
<TextBlock>Surname</TextBlock>
<TextBox Validation.ErrorTemplate="{StaticResource validationTemplate}" HorizontalAlignment="Left" Margin="0" Name="Surname" VerticalAlignment="Top" >
<TextBox.Text>
<Binding Path="Surname" UpdateSourceTrigger="LostFocus" >
<Binding.ValidationRules>
<val:Required />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
As you can see from the code above, I use class Required to validate the field. Function Validate() of class Required then returns ValidationResult object. I also defined some triggers to styles for inputs, so I´m able to show validation result to the user in view.
What I don’t know is how to detect the state of validation of all the inputs in ViewModel. In the ViewModel, I have the SaveUserCanExecute function which should enable/disable registration form submit button on the basic on a validation state of all the inputs.
So is there any simple way how to achieve this?
I could make some workaround for this, but I think is not the proper way.
Now I made a Submit_Click function in a View code behind fired on a Click event of a Submit Button.
In RegisterView.xaml
<Button Content="Register" HorizontalAlignment="Left" Margin="0" Name="Submit" VerticalAlignment="Top" Command="{x:Static inf:Commands.SaveUser}" Click="Submit_Click" />
I also created new public boolean variable “formIsValid” in code behind. When submit button is pressed, then I check whether all inputs has no validation error (with Validation.GetHasError(InputName) function). If so, I set the formIsValid variable to true, otherwise, I set it to false.
In RegisterView.xaml.cs
private void Submit_Click(object sender, RoutedEventArgs e)
{
if (Validation.GetHasError(Firstname) == false && Validation.GetHasError(Surname) == false)
{
registerFormValid = true;
}
else
{
registerFormValid = false;
}
}
Then in ViewModel SaveUserCanExecute function looks like this:
private bool SaveUserCanExecute(string parameter)
{
if (View.registerFormValid == true)
{
return true;
}
return false;
}
But as I mentioned before, I think it´s not the proper way, and I´m looking for some more clear way.
implement IDataErrorInfo in your ViewModel then you have all information you need in your VM. Your XAML just need the ValidatesOnDataErrors=true
EDIT: check the use of DelegeCommand and then your command CanExecute can simply check then for string.IsNullOrEmpty(this.Error).