有没有办法在没有自定义ValidationRules的情况下对int或double进行XAML文本框验证?

时间:2009-10-22 12:36:16

标签: wpf validation xaml textbox

我有一些XAML 文本框除了之外什么都不允许,有些只需要 int

我可以使用 Binding.ValidationRules 及其所有代码,触发器,样式为described here,但这些简单验证无法实现使用类似这样的属性,只有这样的类型可以输入:

伪码:

<TextBox Text="{Binding NumberOfContracts}" SimpleValidation="{x:Type sys:Integer}"/>
<TextBox Text="{Binding ContractPrice}" SimpleValidation="{x:Type sys:Double}"/>

1 个答案:

答案 0 :(得分:2)

我一直在想一些有用的东西,但现在我已经读过你的问题了,我开始写一个。

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace SimpleValidation
{
    public class SimpleValidator : ValidationRule
    {

        #region Validation Attached Property

        public static Type GetValidationType(DependencyObject obj)
        {
            return (Type)obj.GetValue(ValidationTypeProperty);
        }

        public static void SetValidationType(DependencyObject obj, Type value)
        {
            obj.SetValue(ValidationTypeProperty, value);
        }

        // Using a DependencyProperty as the backing store for ValidationType.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ValidationTypeProperty =
            DependencyProperty.RegisterAttached("ValidationType", typeof(Type), typeof(ValidationRule), new UIPropertyMetadata(null, OnValidationTypeChanged));

        private static void OnValidationTypeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var element = obj as FrameworkElement;
            if (element == null) return;

            // When the element has loaded.
            element.Loaded += (s, e) =>
                                  {
                                      // Create a new validator
                                      var validation = new SimpleValidator(args.NewValue as Type);
                                      // Get the binding expression for the textbox property
                                      var binding = BindingOperations.GetBinding(obj, TextBox.TextProperty);
                                      // If not null and doesn't already contain the validator, then add it.
                                      if (binding != null)
                                          if (!binding.ValidationRules.Contains(validation))
                                              binding.ValidationRules.Add(validation);
                                  };
        }

        #endregion


        #region Validation

        public SimpleValidator() { }
        public SimpleValidator(Type validationType)
        {
            ValidationType = validationType;
        }

        public Type ValidationType { get; set; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            try
            {
                // Try to convert to the type specified
                Convert.ChangeType(value, ValidationType);
                // Accept value
                return new ValidationResult(true, "Valid value");
            }
            catch (Exception)
            {
                // return invalid type error.
                return new ValidationResult(false, "Value is not of type " + ValidationType.FullName);
            }
        }

        #endregion

    }
}

用法示例:

<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" validator:SimpleValidator.ValidationType="{x:Type system:Double}" />

确保UpdateSourceTrigger反映了您需要的更新类型,通常是PropertyChanged。我希望你和我一样喜欢它。完整源代码here