使用 ValidationRule 类的 WPF 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18930125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:41:27  来源:igfitidea点击:

WPF validation using ValidationRule class

wpfxaml

提问by Tech Jay

I am trying to add validation on a text for required field using the "ValidationRule" class. I have the following implementation of the class

我正在尝试使用“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);
    }
}

Further in my XAML, i have the following implementation of it:

进一步在我的 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>

and for displaying the error message, i have the following error template style in app.xaml

为了显示错误消息,我在 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>

The code is compiling and running fine. Even the validationRule method is getting hit by the debugger. But the issue is that the message for error is not getting displayed.

该代码正在编译并运行良好。甚至validationRule 方法也被调试器击中。但问题是没有显示错误消息。

I have attached the Model using the following code :

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

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

I am new to the concept of WPF. What am i missing here ? Any help is greatly appreciated.

我是 WPF 概念的新手。我在这里错过了什么?任何帮助是极大的赞赏。

采纳答案by Rohit Vats

Everything is perfect except you are passing isValidto trueeven in case of validation failure -

一切都很完美,除非您在验证失败的情况下传递isValidtrue-

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

It should be false instead -

它应该是假的 -

return new ValidationResult(false, this.ErrorMessage);