要事先必填验证,首先要重写ValidationRule类的Validate方法,然后在Binding中指定对应的ValidationRule。

第一步:重写ValidationRule的Validate

[csharp] view plain copy
 
  1. public class RequiredValidationRule:ValidationRule {  
  2.   
  3.     public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {  
  4.         if (value == null || string.IsNullOrWhiteSpace(value.ToString())) {  
  5.             return new ValidationResult(false, "内容不能为空");  
  6.         }  
  7.         return new ValidationResult(true, null);  
  8.     }  
  9. }  


第二步:窗体:

[html] view plain copy
 
  1. <TextBox Grid.Row="0" Grid.Column="1"   
  2.             Validation.ErrorTemplate="{StaticResource CT_TextBox_Required}"  
  3.             Style="{StaticResource Style_TextBox_Error}"  
  4.     <TextBox.Text>  
  5.         <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">  
  6.             <Binding.ValidationRules>  
  7.                 <vr:RequiredValidationRule />  
  8.             </Binding.ValidationRules>  
  9.         </Binding>  
  10.     </TextBox.Text>  
  11. </TextBox>  


第三步:错误控件的样式

[html] view plain copy
 
  1. <ControlTemplate x:Key="CT_TextBox_Required">  
  2.     <DockPanel>  
  3.         <TextBlock Foreground="Red" FontSize="20" Text="!" />  
  4.         <AdornedElementPlaceholder />  
  5.     </DockPanel>  
  6. </ControlTemplate>  
  7. <Style x:Key="Style_TextBox_Error" TargetType="{x:Type TextBox}">  
  8.     <Setter Property="Margin" Value="10,5,20,5" />  
  9.     <Style.Triggers>  
  10.         <Trigger Property="Validation.HasError" Value="true">  
  11.             <Setter Property="ToolTip"  
  12.                     Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=(Validation.Errors)[0].ErrorContent}" />  
  13.         </Trigger>  
  14.     </Style.Triggers>  
  15. </Style>  


我们来看看效果图:,貌似不错,但是还有不尽人意之处。在控件Focus时,控件内容为空,我希望此时就显示错误提示,而不是更改后再显示错误提示,首先要添加PreviewGotKeyboardFocus事件

[csharp] view plain copy
 
  1. private void TextBox_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {  
  2.     TextBox tb = sender as TextBox;  
  3.     tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();  
  4. }  


好,我们轻松地实现了必填验证

 

http://blog.csdn.net/The_Eyes/article/details/61415096