ValidationRule没有开火

时间:2014-10-26 22:29:17

标签: wpf validation xaml validationrules

我在验证方面遇到了问题,到目前为止,这是一场真正的斗争。我更改了一些代码,并阅读了很多相关内容,并遵循本指南的大部分内容:http://developingfor.net/2009/10/13/using-custom-validation-rules-in-wpf/但我遇到了问题。验证没有解雇,我找不到原因!我将发布一些代码。

    public class RequiredFields : 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(false, this.ErrorMessage);
            }

            return new ValidationResult(true, null);
        }
    }

XAML:

        <Style
x:Key="textBoxInError"
TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger
        Property="Validation.HasError"
        Value="true">
                <Setter
            Property="ToolTip"
            Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}" />
                <Setter
            Property="Background"
            Value="Red" />
                <Setter
            Property="Foreground"
            Value="White" />
            </Trigger>
        </Style.Triggers>
    </Style>

TextBox XAML:

 <TextBox x:Name="txtFirstName" Validation.ErrorTemplate="{StaticResource validationTemplate}" HorizontalAlignment="Left" Height="23" Margin="156,62,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="149">
        <TextBox.Text>
            <Binding Path="FirstName"  UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
                <Binding.ValidationRules>
                    <validators:RequiredFields ErrorMessage="Name is Required" />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

XAML窗口的CodeBehind具有:

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

但由于某种原因,我没有看到事件发生。如果我在ValidationResult中标记断点,它就不会做任何事情。

1 个答案:

答案 0 :(得分:1)

您的ValidationRule RequiredFields也用作DataContext,但未声明属性FirstName。所以Binding实际上是失败的。您应该定义一个单独的ViewModel,如果您仍想使用RequiredFields作为DataContext,则必须添加属性FirstName,如下所示:

public class RequiredFields : ValidationRule, INotifyPropertyChanged
{
    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(false, this.ErrorMessage);
        }

        return new ValidationResult(true, null);
    }
    //Implements INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string prop){
       var handler = PropertyChanged;
       if(handler != null) handler(this, new PropertyChangedEventArgs(prop));
    }
    //add the property FirstName
    string _firstName;
    public string FirstName { 
       get {
           return _firstName;
       }
       set {
          if(_firstName != value) {
             _firstName = value;
             OnPropertyChanged("FirstName");
          }
       }
    }
}

上面的代码只是一个快速修复和示范解决方案,而不是实际操作。您应该创建一些实现INotifyPropertyChanged的基类并实现 单独的 ViewModel,而不是使用现有的ValidationRule。