IDataErrorInfo如何工作?

Ing*_*als 8 wpf idataerrorinfo

我目前正在寻找我的WPF应用程序的验证,并看到提到IDataErrorInfo.但是,很少有如何使用它的指南,更糟糕的是没有人解释它是如何工作的.

在MSND.com网站,这是得到安宁 MSDN

public class Person : IDataErrorInfo
{
    private int age;
    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Error
    {
        get
        {
            return null;
        }
    }

    public string this[string name]
    {
        get
        {
            string result = null;
            if (name == "Age")
            {
                if (this.age < 0 || this.age > 150)
                {
                    result = "Age must not be less than 0 or greater than 150.";
                }
            }
            return result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我看到这里发生了什么,但我不知道它对我的数据有什么影响.

这两个属性何时使用?假设有人设置Age为400:调用属性上的setter.这个错误会阻止它被设置吗?如果没有,它只是警告数字不正确,什么阻止某人保存信息?没有IsValid()方法可以检查,有吗?

很想知道窗帘会发生什么.

jps*_*res 6

Error通常不使用该属性,但您必须定义它才能实现该接口.正如decyclone所说,验证不会阻止使用错误的值设置属性,但您可以将属性设置为默认值.让我告诉你我是如何使用它的.我有几个TextBox我必须验证他们的价值观.我不想在调用集合时显示带有错误的MessageBox,而是采用"webly"方法:TextBox当设置了无效值并且工具提示TextBox显示时,我希望边框和背景为红色它得到的错误.

这是我对TextBox的xaml:

<converters:ValidationConverter x:Key="validationConverter"/>
<Style x:Key="TestStepTextBox" TargetType="{x:Type TextBox}">
    <Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border x:Name="Bd" SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                    <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="Validation.HasError" Value="true">
                        <Setter Property="ToolTip"
                                Value="{Binding RelativeSource={RelativeSource Self}, 
                                Converter={StaticResource validationConverter}, Path=(Validation.Errors)}"/>
                        <Setter Property="Background" Value="#33FF342D"/>
                        <Setter Property="BorderBrush" Value="#AAFF342D"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<TextBox Name="txtRunAfter" Text="{Binding RunAfter, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}" Style="{DynamicResource TestStepTextBox}"/>
<TextBox Name="txtStopAfter" Text="{Binding StopAfter, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}" Style="{DynamicResource TestStepTextBox}"/>
Run Code Online (Sandbox Code Playgroud)

关于转换器的一个非常重要的说明.当我输入无效值然后设置了一个好的值时,我得到了一个例外.不知何故,可能与UpdateSourceTrigger=PropertyChangedhas 有关,有一段时间HasError属性为true但没有设置错误(参见链接).所以这是转换器的代码:

public class ValidationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ReadOnlyObservableCollection<ValidationError> errors = value as ReadOnlyObservableCollection<ValidationError>;
        if (errors == null) return value;
        if (errors.Count > 0)
        {
            return errors[0].ErrorContent;
        }
        return "";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException("This method should never be called");
    }
}
Run Code Online (Sandbox Code Playgroud)

为了防止将隐藏值保存到我的模型层,我使用相同的方法来检查是否应该将数据提交给模型.如果值无效,我只需设置属性,不要在模型中调用一组属性.检查代码:

private int _runAfter = 0;
public int RunAfter
{
    get
    {
        return _runAfter;
    }

    set
    {
        if (_runAfter != value)
        {
            _runAfter = value;
            OnPropertyChanged("RunAfter");

            if (validateRunAfter() == null)
                setRunAfter(); //sets the property value to the model layer
        }
    }
}

string IDataErrorInfo.this[string columnName]
{
    get
    {
        string message = null;
        if (columnName == "RunAfter")
            message = validateRunAfter();
        //...
        return message;
    }
}

private string validateRunAfter()
{
    if (value >= _order)
        return "Run After value must be less than its Step Order (#) value.";

    return null;
}
Run Code Online (Sandbox Code Playgroud)