2009-10-22 35 views

回答

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

相關問題