使用ValidationRule类进行WPF验证

时间:2013-09-21 07:35:17

标签: wpf xaml

我正在尝试使用“ValidationRule”类在必填字段的文本上添加验证。我有以下类

的实现
using System.Windows.Controls;
using System.Globalization;

public class RequiredField : ValidationRule
{
    private String _errorMessage = String.Empty;
    public string ErrorMessage
    {
        get { return _errorMessage; }
        set { _errorMessage = value; }
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var str = value as string;

        if (String.IsNullOrEmpty(str))
        {
            return new ValidationResult(true, this.ErrorMessage);
        }

        return new ValidationResult(true, null);
    }
}

此外,在我的XAML中,我有以下实现:

      <TextBox Grid.Row="1" Grid.Column="3"  Name="txtUserName"  Height="23" VerticalAlignment="Top" Width="70" Grid.ColumnSpan="2" HorizontalAlignment="Left" MaxLength="50">
        <TextBox.Text>
            <Binding Path="Username" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <validators:RequiredField ErrorMessage="username is required." />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>

    </TextBox>

并且为了显示错误消息,我在app.xaml中有以下错误模板样式

            <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">

                            <TextBlock DockPanel.Dock="Right"
                            Foreground="Orange"
                            Margin="5" 
                            FontSize="12pt"
                            Text="{Binding ElementName=MyAdorner, 
                           Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                            </TextBlock>

                            <Border BorderBrush="Green" BorderThickness="3">
                                <AdornedElementPlaceholder Name="MyAdorner" />
                            </Border>

                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
                    Value="{Binding RelativeSource={RelativeSource Self}, 
                   Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>

代码正在编译并正常运行。即使是validationRule方法也会受到调试器的攻击。 但问题是错误消息未显示。

我使用以下代码附加了模型:

 ApplicationUsersUIContract ss = new ApplicationUsersUIContract();
                         this.DataContext = ss;

我是WPF概念的新手。我在这里失踪了什么?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

除非您在验证失败的情况下将isValid传递给true,否则一切都很完美 -

    if (String.IsNullOrEmpty(str))
    {
        return new ValidationResult(true, this.ErrorMessage); <--- HERE        
    }

它应该是假的 -

return new ValidationResult(false, this.ErrorMessage);