可以做一个虚假的绑定,比如绑定到自身:
-
<StackPanel>
-
<TextBox>
-
<TextBox.Text>
-
<Binding RelativeSource="{RelativeSource Self}" Path="Tag" UpdateSourceTrigger="PropertyChanged">
-
<Binding.ValidationRules>
-
<local:RangeRule Min="0" Max="20" />
-
</Binding.ValidationRules>
-
</Binding>
-
</TextBox.Text>
-
</TextBox>
-
</StackPanel>
-
public class RangeRule : ValidationRule
-
{
-
public int Min { get; set; }
-
public int Max { get; set; }
-
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
-
{
-
int num;
-
if (!int.TryParse(value as string, out num) || num < Min || num > Max)
-
return new ValidationResult(false, "Please enter a number in the range: " + Min + " - " + Max + ".");
-
else
-
return new ValidationResult(true, null);
-
}