0

We are making a project to the university with some of my classmates. We have to do a desktop application and we've got some problem with it. It was basically very difficult to understand the MVVM, but i have some issue with the validation. First we wanted to use the INotifyDataErrorInfo interface for the validation, because the teacher recommended this, but we didn't understand it.

So we solved the validation with ValidationRules like this:

public class CantBeNullRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string charString = value as string;
        if (charString.Length == 0)
        {
            return new ValidationResult(false, $"The box can't be empty");
        }
        return new ValidationResult(true, null);
    }
}

And we bind these validations for the textboxes on a view:

<TextBox x:Name="pwdPassword" Grid.Column="2" Grid.Row="4" Grid.ColumnSpan="4" BorderThickness="0,0,0,1" VerticalAlignment="Bottom" BorderBrush="#FF5DC2D5" Foreground="Black" SelectionBrush="#FF5DC2D5" FontFamily="Open Sans SemiBold" FontSize="10">
        <TextBox.Text>
            <Binding Path="Password" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <rule:CantBeNullRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

The problem is that, this "CantBeNull" rules wont execute when we open the view, first we have to write in something into the textbox. I would like that check every validation on view when i click on a button. If one of the validatons is false, then write out the errormessage, else execute the command.

We want to use these ValidationRules, so we are waiting answers for this kind of validation.

AME
  • 302
  • 2
  • 17

1 Answers1

0

I think that the rule is only fired when the binding is updated, which you've set to 'PropertyChanged'.

Personally I'd put the validation on the ViewModel, not the view (although that does require using INotifyDataErrorInfo). That way the ViewModel's constructor can set a default value for Password (of blank), which would trigger the validation rule.

INotifyDataErrorInfo might seem like a lot of effort for a simple application, but it's well worth getting to know. Once you've got it set up, it's very slick and adding new validation rules is quick and easy. There are some useful links here

Robin Bennett
  • 3,192
  • 1
  • 8
  • 18