The method I used is to create different styles in which my custom validation is embedded. Then it's just a matter of assigning the right style at runtime, which contains the necessary validation.
EDIT
The following is a basic example that creates a NumericTextBox style:
<Style x:Key="NumericTextBox"> <Setter Property="TextBox.VerticalAlignment" Value="Stretch"/> <Setter Property="TextBox.VerticalContentAlignment" Value="Center"/> <Setter Property="TextBox.Height" Value="24"/> <Setter Property="TextBox.Margin" Value="0,2,0,2"/> <EventSetter Event="UIElement.PreviewTextInput" Handler="tbx_DigitCheck"/> <EventSetter Event="UIElement.PreviewKeyDown" Handler="tbx_OtherCharCheck"/> <EventSetter Event="UIElement.PreviewDragEnter" Handler="tbx_PreviewDragEnter"/> </Style>
The following method is specified in the code file for the resource dictionary in which the style is stored. This method ensures that only numbers and a valid decimal separator can be entered in the text box. Each character is validated before it is actually displayed in the text box.
Public Sub tbx_DigitCheck(ByVal sender As Object, _ ByVal e As TextCompositionEventArgs) //Retireve the sender as a textbox. Dim tbx As TextBox = CType(sender, TextBox) Dim val As Short //Get the current decimal separator. Dim dSep As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator //Check to make sure that a decimal separator character has not //already been entered in the textbox. Only make this check //for areas of the text that are not selected. If e.Text = dSep And tbx.SelectedText.Contains(dSep) Then //Do Nothing. Allow the character to be typed. ElseIf e.Text = dSep And tbx.Text.Contains(dSep) Then e.Handled = True End If //Only allow the decimal separator and numeric digits. If Not Int16.TryParse(e.Text, val) And Not e.Text = dSep Then e.Handled = True End If End Sub
source share