2009-08-28 45 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