Reputation: 1160
Say I am trying to implement a piece of functionality in which a text box only allows integers to be inputted in by the user. I can implement this two ways, using a ValidationRule that checks whatever the user inputs and binding it to the text property through the XAML or I can create a new behavior and attach it to the control (not through binding).
Examples of the XAML on both:
Behavior:
<TextBox behaviors:DigitsOnlyBehavior.IsDigitOnly="True"/>
ValidationRule which binds to the Window's 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?
Upvotes: 4
Views: 1425
Reputation: 6316
With Behaviors I like and expect a "positive" scenario/workflow without errors. The focus is no errors. The user gets pretty quickly that when they type an 'a
' in the TextBox with Numeric behavior that it doesn't take it, that it's a numeric textbox, and this is how it works.
With Validation, the focus seems to be more on the error. I can have a Numeric TextBox, but I also don't take numbers beyond 100, if you type '101
', I let you know that this is not acceptable. The focus here is to guide user into what is unacceptable by throwing a validation error.
Behavior Advantages:
Behavior Disadvantage:
-could be confusing , so if you put the logic not to accept '101', there is no default way to guide the user.
Upvotes: 0