要事先必填验证,首先要重写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>
- 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