0
我有一些XAML 文本框,需要什麼都不允許,但雙和一些需要什麼都不需要,但int。有沒有辦法讓XAML文本框在int或double上驗證而沒有自定義ValidationRules?
我可以用Binding.ValidationRules其所有的代碼背後,觸發器,樣式,described here,但不存在這些簡單驗證的方式來使用屬性這樣的事情,只是讓那件事
僞代碼:類型可以鍵入
我有一些XAML 文本框,需要什麼都不允許,但雙和一些需要什麼都不需要,但int。有沒有辦法讓XAML文本框在int或double上驗證而沒有自定義ValidationRules?
我可以用Binding.ValidationRules其所有的代碼背後,觸發器,樣式,described here,但不存在這些簡單驗證的方式來使用屬性這樣的事情,只是讓那件事
僞代碼:類型可以鍵入
我一直想過索姆這件事很有用,但現在我已經閱讀了你的問題,我開始寫一篇。
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。