I want to validate some Text in a TextBlock
TextBlock xaml:
<TextBlock x:Name="numInput" Validation.ErrorTemplate="{StaticResource errorTemplate}" > <TextBlock.Text> <Binding Path="Text" RelativeSource="{RelativeSource self}" NotifyOnValidationError="True"> <Binding.ValidationRules> <local: NumberValidator /> </Binding.ValidationRules> </Binding> </TextBlock.Text> </TextBlock> The Text is added in codebehind by some button clicks in the GUI (i.e. a touch screen)
errorTemplate
<ControlTemplate x:Key="errorTemplate"> <StackPanel> <TextBlock Foreground="Red">error msg</TextBlock> <AdornedElementPlaceholder/> </StackPanel> </ControlTemplate> NumberValidator
class NumberValidator : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { Console.WriteLine("validating numbers!!"); int num = -1; try { num = Int32.Parse(value.ToString()); } catch (Exception e) { return new ValidationResult(false, "input must be numbers!"); } if (num > 999 || num < 1) { return new ValidationResult(false, string.Format("must be integers from {0} to {1}", 1, 999)); } return new ValidationResult(true, null); } } Questions:
No error message is shown. In fact,
NumberValidatorisn't even called. Why?How to validate the error only when a
Buttonis clicked?How to pass valid range (i.e min, max) information to the
NumberValidator?
Thanks!