2009-08-28 48 views
10

我目前工作的一个WPF应用程序,我想有一个TextBox只能有它的数字条目。我知道我可以验证它的内容时,我失去焦点,并阻止系统的数字内容,但在其他Windows窗体应用程序中,我们用它来完全阻止任何输入数值除外被记录下来。另外,我们使用将该代码放在单独的dll中以在许多地方引用它。验证的文本框在WPF

这里是2008年的代码不使用WPF:

Public Shared Sub BloquerInt(ByRef e As System.Windows.Forms.KeyPressEventArgs, ByRef oTxt As Windows.Forms.TextBox, ByVal intlongueur As Integer) 
    Dim intLongueurSelect As Integer = oTxt.SelectionLength 
    Dim intPosCurseur As Integer = oTxt.SelectionStart 
    Dim strValeurTxtBox As String = oTxt.Text.Substring(0, intPosCurseur) & oTxt.Text.Substring(intPosCurseur + intLongueurSelect, oTxt.Text.Length - intPosCurseur - intLongueurSelect) 

    If IsNumeric(e.KeyChar) OrElse _ 
     Microsoft.VisualBasic.Asc(e.KeyChar) = System.Windows.Forms.Keys.Back Then 
     If Microsoft.VisualBasic.AscW(e.KeyChar) = System.Windows.Forms.Keys.Back Then 
      e.Handled = False 
     ElseIf strValeurTxtBox.Length < intlongueur Then 
      e.Handled = False 
     Else 
      e.Handled = True 

     End If 
    Else 
     e.Handled = True 
    End If 

是否有WPF等效的方法?我不会介意,如果这是一个风格,但我是新来WPF这样的风格都有点晦涩他们可以或不可以做。

回答

23

只能用在文本框的附加属性限制输入数字。定义附加属性一次(即使在单独的dll中),并在任何TextBox上使用它。这里是附加属性:

using System; 
    using System.Windows; 
    using System.Windows.Controls; 
    using System.Windows.Input; 

    /// <summary> 
    /// Class that provides the TextBox attached property 
    /// </summary> 
    public static class TextBoxService 
    { 
     /// <summary> 
     /// TextBox Attached Dependency Property 
     /// </summary> 
     public static readonly DependencyProperty IsNumericOnlyProperty = DependencyProperty.RegisterAttached(
     "IsNumericOnly", 
     typeof(bool), 
     typeof(TextBoxService), 
     new UIPropertyMetadata(false, OnIsNumericOnlyChanged)); 

     /// <summary> 
     /// Gets the IsNumericOnly property. This dependency property indicates the text box only allows numeric or not. 
     /// </summary> 
     /// <param name="d"><see cref="DependencyObject"/> to get the property from</param> 
     /// <returns>The value of the StatusBarContent property</returns> 
     public static bool GetIsNumericOnly(DependencyObject d) 
     { 
     return (bool)d.GetValue(IsNumericOnlyProperty); 
     } 

     /// <summary> 
     /// Sets the IsNumericOnly property. This dependency property indicates the text box only allows numeric or not. 
     /// </summary> 
     /// <param name="d"><see cref="DependencyObject"/> to set the property on</param> 
     /// <param name="value">value of the property</param> 
     public static void SetIsNumericOnly(DependencyObject d, bool value) 
     { 
     d.SetValue(IsNumericOnlyProperty, value); 
     } 

     /// <summary> 
     /// Handles changes to the IsNumericOnly property. 
     /// </summary> 
     /// <param name="d"><see cref="DependencyObject"/> that fired the event</param> 
     /// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param> 
     private static void OnIsNumericOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
     bool isNumericOnly = (bool)e.NewValue; 

     TextBox textBox = (TextBox)d; 

     if (isNumericOnly) 
     { 
      textBox.PreviewTextInput += BlockNonDigitCharacters; 
      textBox.PreviewKeyDown += ReviewKeyDown; 
     } 
     else 
     { 
      textBox.PreviewTextInput -= BlockNonDigitCharacters; 
      textBox.PreviewKeyDown -= ReviewKeyDown; 
     } 
     } 

     /// <summary> 
     /// Disallows non-digit character. 
     /// </summary> 
     /// <param name="sender">The source of the event.</param> 
     /// <param name="e">An <see cref="TextCompositionEventArgs"/> that contains the event data.</param> 
     private static void BlockNonDigitCharacters(object sender, TextCompositionEventArgs e) 
     { 
     foreach (char ch in e.Text) 
     { 
      if (!Char.IsDigit(ch)) 
      { 
       e.Handled = true; 
      } 
     } 
     } 

     /// <summary> 
     /// Disallows a space key. 
     /// </summary> 
     /// <param name="sender">The source of the event.</param> 
     /// <param name="e">An <see cref="KeyEventArgs"/> that contains the event data.</param> 
     private static void ReviewKeyDown(object sender, KeyEventArgs e) 
     { 
     if (e.Key == Key.Space) 
     { 
      // Disallow the space key, which doesn't raise a PreviewTextInput event. 
      e.Handled = true; 
     } 
     } 
    } 

这里是如何使用它(取代“控制”与您自己的命名空间):

<TextBox controls:TextBoxService.IsNumericOnly="True" /> 
+1

我会尝试。 我想,我几乎可以添加这样的事情。例如,里面的文本的最大长度,这也是我的另一个问题。 – 2009-08-31 13:18:20

+0

忘了提,这是一个浮点数(小数和整数部分的最大数量的最大数量)的最大长度 – 2009-08-31 14:21:07

+1

是,附加属性是非常强大的,并允许你添加所有类型的行为。 – 2009-08-31 18:17:34

4

您可以将验证您的这个例子绑定(我的程序)

<TextBox> 
     <TextBox.Text> 
       <Binding Path="CategoriaSeleccionada.ColorFondo" 
         UpdateSourceTrigger="PropertyChanged"> 
        <Binding.ValidationRules> 
          <utilities:RGBValidationRule /> 
        </Binding.ValidationRules> 
       </Binding> 
     </TextBox.Text> 
</TextBox> 

看,你把里面的验证这样的绑定。随着UpdateSourceTrigger当你绑定将被更新,您可以更改(失去重心,在每一个变化......)

好,验证是一类,我会放你一个例子:

class RGBValidationRule : ValidationRule 
{ 
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
    { 
     // Here you make your validation using the value object. 
     // If you want to check if the object is only numbers you can 
     // Use some built-in method 
     string blah = value.ToString(); 
     int num; 
     bool isNum = int.TryParse(blah, out num); 

     if (isNum) return new ValidationResult(true, null); 
     else return new ValidationResult(false, "It's no a number"); 
    } 
} 

总之,执行该方法内的工作并返回一个新的ValidationResult。第一个参数是bool,如果验证是好的,则为true,否则为false。第二个参数只是一个信息消息。

我认为这是文本框验证的基础知识。

希望得到这个帮助。

编辑:对不起,我不知道VB.NET,但我认为C#代码非常简单。

+0

我知道这两个,因此很容易对我来说,它CONVER。 谢谢,我会尽快尝试。 – 2009-08-28 12:58:25