Search code examples
c#.netwpfxamlvalidationrule

Passing value in a TextBox to a ValidationRule


I have two TextBox controls (as follows) and would like to pass the Text of the first TextBox [x:Name="defPointFrom1Txt"] into the ValidationRule [MinIntegerValidationRule] for the second TextBox [x:Name="defPointTo1Txt"] instead of the current value of 1. I could do this in code by naming the validation rule and setting based off an event when the value in the first TextBox changes. However, is there a way to do this in the XAML to keep all the validation logic in one place?

            <TextBox x:Name="defPointFrom1Txt" Grid.Row="2" Grid.Column="1" Style="{StaticResource lsDefTextBox}" 
                     Text="{Binding Path=OffensePointsAllowed[0].From}" IsEnabled="False"/>
            <TextBox x:Name="defPointTo1Txt" Grid.Row="2" Grid.Column="2" Style="{StaticResource lsDefTextBox}"
                     LostFocus="defPointTo1Txt_LostFocus">
                <TextBox.Text>
                    <Binding Path="OffensePointsAllowed[0].To" StringFormat="N1">
                        <Binding.ValidationRules>
                            <gui:MinIntegerValidationRule Min="1"/>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>

My validation rule code is below for completeness.

  public class IntegerValidationRule : ValidationRule
{

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        float controlValue;
        try
        {
            controlValue = int.Parse(value.ToString());
        }
        catch (FormatException)
        {
            return new ValidationResult(false, "Value is not a valid integer.");
        }
        catch (OverflowException)
        {
            return new ValidationResult(false, "Value is too large or small.");
        }
        catch (ArgumentNullException)
        {
            return new ValidationResult(false, "Must contain a value.");
        }
        catch (Exception e)
        {
            return new ValidationResult(false, string.Format("{0}", e.Message));
        }
        return ValidationResult.ValidResult;
    }

}

public class MinIntegerValidationRule : IntegerValidationRule
{
    public int Min { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {

        ValidationResult retValue = base.Validate(value, cultureInfo);
        if (retValue != ValidationResult.ValidResult)
        {
            return retValue;
        }
        else
        {
            float controlValue = int.Parse(value.ToString());
            if (controlValue < Min)
            {
                return new ValidationResult(false, string.Format("Please enter a number greater than or equal to {0}.",Min)); 
            }
            else
            {
                return ValidationResult.ValidResult;
            }
        }
    }
}

UPDATE:

In response to the below answers I am attempting to create a DependencyObject. I did that as follows, but don't know how to use that in the ValidationRule code (or even that I created it properly).

public abstract class MinDependencyObject : DependencyObject
{
    public static readonly DependencyProperty MinProperty =
      DependencyProperty.RegisterAttached(
      "Min", typeof(int), 
      typeof(MinIntegerValidationRule),
      new PropertyMetadata(), 
      new ValidateValueCallback(ValidateInt)
      );

    public int Min
    {
        get { return (int)GetValue(MinProperty); }
        set { SetValue(MinProperty, value); }
    }
    private static bool ValidateInt(object value)
    {
        int test;
        return (int.TryParse(value.ToString(),out test));
    }
}

Solution

  • This post Attaching a Virtual Branch to the Logical Tree in WPF By Josh Smith, 6 May 2007 outlines a solution to this issue.