WPF文本框中的验证 [英] Validation in textbox in WPF

查看:62
本文介绍了WPF文本框中的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个 WPF 应用程序,我希望在其中有一个只能包含数字条目的 TextBox.我知道当我失去焦点并阻止内容为数字时,我可以验证它的内容,但在其他 Windows 窗体应用程序中,我们使用完全阻止除数字之外的任何输入被写下.另外,我们习惯于将该代码放在一个单独的 dll 中,以便在许多地方引用它.

I am currently working on a WPF application where I would like to have a TextBox that can only have numeric entries in it. I know that I can validate the content of it when I lost the focus and block the content from being numeric, but in other Windows Form application, we use to totally block any input except numerical from being written down. Plus, we use to put that code in a separate dll to reference it in many places.

这是 2008 年未使用 WPF 的代码:

Here is the code in 2008 not using 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 的新手,所以风格对于他们能做什么或不能做什么有点模糊.

Is there an equivalent way in WPF? I wouldn't mind if this is in a style but I am new to WPF so style are a bit obscure to what they can or can't do.

推荐答案

您可以仅使用 TextBox 上的附加属性将输入限制为数字.定义一次附加属性(即使在单独的 dll 中)并在任何 TextBox 上使用它.这是附加的属性:

You can restrict the input to numbers only using an attached property on the TextBox. Define the attached property once (even in a separate dll) and use it on any TextBox. Here is the attached property:

   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;
         }
      }
   }

这里是如何使用它(用你自己的命名空间替换控件"):

Here is how to use it (replace "controls" with your own namespace):

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

这篇关于WPF文本框中的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆