运行时的 WPF Binding.ValidationRules

标签 wpf dynamic validationrules

我正在为 XAML 中的各种控件编写验证规则。我想在运行时将validationRules 附加到控件,而不是在XAML 中。我正在考虑使用 Converters 。但是任何想法/想法都可以更好地实现这一目标。

示例代码:

 <TextBox Name="txtFirstName" >   <TextBox.Text>  <Binding Path="FirstName" 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();
    }
}

谢谢,

最佳答案

我使用的一种方法是创建不同的样式,其中内置了我的自定义验证。然后只需在运行时分配包含所需验证的正确样式即可。

编辑

下面是一个创建名为 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>

以下方法放置在存储样式的资源字典的代码隐藏文件中。此方法确保只能在文本框中输入数字和有效的小数点分隔符。每个字符在实际显示在文本框中之前都会检查其有效性。
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

关于运行时的 WPF Binding.ValidationRules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7066474/

相关文章:

c# - 如何从 FluentValidation 获取验证规则

c# - 使用 IValueConverter 验证可为 null int

c# - 如何设置按钮悬停并单击前景的样式?

wpf - 相对源与元素名称

c# - 将元素插入源后 WPF DataGrid 不更新

C++ 动态内存细节

exec 的 Python 变量作用域?

wpf - DrawingVisual 未刷新

c - 如何使用函数动态分配字符串?

java - 在java中验证对象的最佳方法