-1

I've followed Microsoft's short tutorial on implementing binding validation in WPF and it's working nicely.

However, I need to expose the result of the validation on the view model, so that my application can prevent the user progressing, but I can't see a way to achieve this.

The XAML for my control is below, with StartDateRule defined as a class that inherits from ValidationRule

<controls:DateInputBox
    Grid.Column="2"
    Grid.Row="3"
    Height="28"
    HorizontalAlignment="Left"
    Watermark=""
    Width="110"
    VerticalAlignment="Center">
    <controls:DateInputBox.SelectedDate>
        <Binding Path="SelectedDate">
            <Binding.ValidationRules>
                <local:StartDateRule/>
            </Binding.ValidationRules>
        </Binding>
    </controls:DateInputBox.SelectedDate>
</controls:DateInputBox>

I tried to create an instance of the StartDateRule class in my view model, and bind to this. The idea being that I can expose some Validate() method on the view model that would call the Validate() method on the rule. But I can't seem to create this binding. I'm not sure if this is because I don't have the syntax right, or because it's just not possible.

I've read a lot of stuff on using the INotifyDataErrorInfo interface, but this seems to have a lot of boilerplate code, and I can't find good official documentation on this.

Is what I'm trying to achieve possible?

amarsha4
  • 453
  • 6
  • 21
  • Validationrules happen in the view. The input does not transfer to the viewmodel. You'd have to capture the bubbling error in the view and pass something to viewmodel. Or validate in the viewmodel – Andy Dec 08 '21 at 18:29

1 Answers1

1

You don't create instances of validation rules in a view model. If you have a view model, you should implement your application logic in there and this applies to the validation logic as well.

This means that you should implement the INotifyDataErrorInfo interface instead of using validation rules in the view. Please refer to this blog post for more information about data validation in WPF in general.

You'll find an example of how to implement the interface here and here.

mm8
  • 163,881
  • 10
  • 57
  • 88