要事先必填验证,首先要重写ValidationRule类的Validate方法,然后在Binding中指定对应的ValidationRule。
第一步:重写ValidationRule的Validate
- public class RequiredValidationRule:ValidationRule {
- public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
- if (value == null || string.IsNullOrWhiteSpace(value.ToString())) {
- return new ValidationResult(false, "内容不能为空");
- }
- return new ValidationResult(true, null);
- }
- }
第二步:窗体:
- <TextBox Grid.Row="0" Grid.Column="1"
- Validation.ErrorTemplate="{StaticResource CT_TextBox_Required}"
- Style="{StaticResource Style_TextBox_Error}"
- <TextBox.Text>
- <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
- <Binding.ValidationRules>
- <vr:RequiredValidationRule />
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
第三步:错误控件的样式
- <ControlTemplate x:Key="CT_TextBox_Required">
- <DockPanel>
- <TextBlock Foreground="Red" FontSize="20" Text="!" />
- <AdornedElementPlaceholder />
- </DockPanel>
- </ControlTemplate>
- <Style x:Key="Style_TextBox_Error" TargetType="{x:Type TextBox}">
- <Setter Property="Margin" Value="10,5,20,5" />
- <Style.Triggers>
- <Trigger Property="Validation.HasError" Value="true">
- <Setter Property="ToolTip"
- Value="{Binding RelativeSource={x:Static RelativeSource.Self},Path=(Validation.Errors)[0].ErrorContent}" />
- </Trigger>
- </Style.Triggers>
- </Style>
我们来看看效果图:,貌似不错,但是还有不尽人意之处。在控件Focus时,控件内容为空,我希望此时就显示错误提示,而不是更改后再显示错误提示,首先要添加PreviewGotKeyboardFocus事件
- private void TextBox_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
- TextBox tb = sender as TextBox;
- tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
- }
好,我们轻松地实现了必填验证
http://blog.csdn.net/The_Eyes/article/details/61415096