Lord Relix
Lord Relix

Reputation: 942

ValidationRule not firing

I am having problems with validations and so far its been a real struggle. I changed around some code and read a lot about this, and followed this guide most of the road: http://developingfor.net/2009/10/13/using-custom-validation-rules-in-wpf/ but I am having problems. The Validation is not firing and I can't find the reason why! I'll post some of my code.

    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>

The CodeBehind for the XAML Window has this:

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

Yet for some reason I won't see the events firing. If I mark a breakpoint in the ValidationResult it won't do anything.

Upvotes: 0

Views: 864

Answers (1)

King King
King King

Reputation: 63317

Your ValidationRule RequiredFields is also used as the DataContext but the property FirstName is not declared. So the Binding is in fact failed. You should define a separate ViewModel, in case if you still want to use the RequiredFields as DataContext, you have to add the property FirstName like this:

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");
          }
       }
    }
}

The code above is just a quick fix and a demonstrative solution rather than actual practice. You should such as create some base class implementing INotifyPropertyChanged and implement separate ViewModel rather than use some existing ValidationRule.

Upvotes: 1

Related Questions