开发者

WPF Binding.ValidationRules at Runtime

开发者 https://www.devze.com 2023-03-28 09:14 出处:网络
I\'m in the process of writing validation Rules to various controls in XAML. I would like to attach validationRules to controls at runtime and not in XAML. I was thinking of using Converters . but any

I'm in the process of writing validation Rules to various controls in XAML. I would like to attach validationRules to controls at runtime and not in XAML. I was thinking of using Converters . but any ideas / thoughts which would be better way to accomplish this.

Sample code:

 <TextBox Name="txtFirstName" >   <TextBox.Text>  <Binding Path="Fi开发者_Python百科rstName" ValidatesOnDataErrors="True" PropertyChanged" >
          <Binding.ValidationRules>
                <Binding Converter="{StaticResource validationConverter}"/>
           </Binding.ValidationRules>             
    </Binding>                                               

public class ValidationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        Binding b = new Binding();
        b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        b.ValidatesOnDataErrors = true;
        b.NotifyOnValidationError = true;
        b.ValidationRules.Add(new RangeValidationRule { ErrorMessage = "Error shown from Converter ", MinValue = 10, MaxValue = 50 });
        return b;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Thanks,


A method that I have used is to create different Styles that have my custom validation built into them. Then it is just a matter of assigning the proper Style at runtime that contains the validation that is needed.

EDIT

Below is a basic example that creates a style called NumericTextBox:

<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 put in the code-behind file for the resource dictionary where the Style is stored. This method makes sure that only numbers and the valid decimal separator can be entered in the textbox. Each character is checked for vailidity before it is actually displayed in the textbox.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号