Next, we will continue to study the data instruction features in the previous topic. First, we will use a simple rageattribute to solve the problem, and then add an age attribute and rangeattribute to the previous example.
[Range (20, 60, errormessage = "the age range is between 20 and 60. ")] [Display (name =" Age ", description =" Singer's age. ")] Public int age {Get; set ;}
Then complete the XAML.
<sdk:Label x:Name="lbAge" Target="{Binding ElementName=txtAge}" Grid.Column="0" Grid.Row="2" FontSize="14" Margin="1,1,20,1"/> <StackPanel Grid.Column="1" Grid.Row="2" Orientation="Horizontal"> <TextBox x:Name="txtAge" Margin="1,1" Width="165" Text="{Binding Age}"/> <sdk:DescriptionViewer Target="{Binding ElementName=txtAge}"/> </StackPanel>
Is it okay? Run the command. The defined range is 20-60. Enter 100 and then remove the focus text box. The result shows that verification has not occurred. Well, it's not easy. Continue to explore and change the attribute definition to the following:
Int m_age = 20; [range (20, 60, errormessage = "the age range is between 20 and 60. ")] [Display (name =" Age ", description =" Singer's age. ")] Public int age {get {return this. m_age;} set {validator. validateproperty (value, new validationcontext (this, null, null) {membername = "Age"}); this. m_age = value ;}}
Run it again! Or not. Why? The validator verification method is also called. Why not? Do not be discouraged. Continue. Do you still remember whether the bound extension mark is written in XAML? Remember? 1. One-way binding mode = oneway by default; 2. Verification is not explicitly set. Well, now I understand. Change it again.
<TextBox x:Name="txtAge" Margin="1,1" Width="165" Text="{Binding Age,Mode=TwoWay,ValidatesOnExceptions=true, NotifyOnValidationError=true}"/>
Run again. This time the verification is completed. However, an exception is thrown. Is there a way to display friendly error prompts without throwing an exception? The answer is, of course, validationsummary.
<sdk:ValidationSummary Grid.Row="3" Grid.ColumnSpan="2"/>
Press F5 again and an exception will still be thrown after verification fails. At this time, You may be disappointed.
There is no way to answer questions, and it will be successful. At this time, you right-click the project and choose View in the browser.
Now, let's summarize the Methods:
1. Add the corresponding features when defining public attributes, such as rangeattribute;
2. Call validator's validateproperty method on the set accessors of the attribute;
3. When binding in XAML or foreground, set the binding mode to twoway, validatesonexceptions and notifyonvalidationerror to true;
4. Add the validationsummary control to display the Error List. Of course, you can check the following if no error list is added.
5. Run the program in non-debug mode.