ValidationRule vs Behavior in WPF

Let's say I'm trying to implement a piece of functionality in which a text field allows only integers to be entered by the user. I can implement these two methods using a ValidationRule that checks that the user types and binds it to the text property via XAML, or I can create a new behavior and attach it to the control (and not through the binding).

XAML examples for both:

Behavior: <TextBox behaviors:DigitsOnlyBehavior.IsDigitOnly="True"/>

ValidationRule that binds to the Window Text property

 <TextBox> <TextBox.Text> <Binding RelativeSource = "{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="Text" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay"> <Binding.ValidationRules> <utils:RestrictInputTypeValidator Restriction="IntegersOnly" ValidatesOnTargetUpdated="True"/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> 

What are the advantages and disadvantages of these approaches? When should I use them? Or is it a matter of preference?

+4
source share
1 answer

With the behavior, I like and expect a “positive” script / workflow without errors. There are no errors in focus. The user gets pretty quickly that when they type ' a ' into a TextBox with a Numeric behavior that they don’t accept, it is a numeric text field, and so it works.

When checking, the focus seems to be more related to the error. I can have a numeric text box, but I also do not accept numbers outside 100, if you type " 101 ", I will let you know that this is unacceptable. The focus here is on how the user enters an invalid value, causing a validation error.

The benefits of behavior:

  • Prevention (you do not allow the user to shoot himself in the leg) by entering bad data.
  • The model remains clean. TextBox Binding does not even get into the setter, since the behavior prevents it, therefore, XAML does not start using PropertChanges or ValidationErrors, etc.

Behavior Disadvantage:

- it can be confusing, therefore, if you put the logic so that it does not accept "101", by default the user cannot use the default method.

0
source

Source: https://habr.com/ru/post/1492127/


All Articles