2009-08-28 40 views
10

Tôi hiện đang làm việc trên một ứng dụng WPF nơi tôi muốn có một TextBox mà chỉ có thể có các mục số trong đó. Tôi biết rằng tôi có thể xác nhận nội dung của nó khi tôi mất tiêu điểm và chặn nội dung không bị số, nhưng trong ứng dụng Biểu mẫu Windows khác, chúng tôi sử dụng để chặn hoàn toàn bất kỳ đầu vào nào ngoại trừ số được viết ra. Thêm vào đó, chúng tôi sử dụng để đặt mã đó trong một dll riêng biệt để tham chiếu nó ở nhiều nơi.Xác thực trong hộp văn bản trong WPF

Dưới đây là đoạn code trong năm 2008 không sử dụng 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 

Có một cách tương đương trong WPF? Tôi sẽ không quan tâm nếu đây là một phong cách nhưng tôi mới để WPF nên phong cách là một chút che khuất những gì họ có thể hoặc không thể làm.

Trả lời

23

Bạn có thể hạn chế đầu vào thành số chỉ bằng cách sử dụng thuộc tính được đính kèm trên Hộp văn bản. Xác định thuộc tính đính kèm một lần (ngay cả trong một dll riêng biệt) và sử dụng nó trên bất kỳ TextBox nào. Dưới đây là tài sản kèm theo:

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

ở đây là làm thế nào để sử dụng nó (thay thế "kiểm soát" với không gian tên riêng của bạn):

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

Tôi sẽ thử điều đó. Tôi tưởng tượng rằng tôi hầu như có thể thêm bất cứ thứ gì như thế. Ví dụ, độ dài tối đa của văn bản bên trong, đó cũng là một vấn đề khác mà tôi có. –

+0

Quên đề cập đến, đó là độ dài tối đa của một số động (số lượng thập phân và số tối đa của số nguyên) –

+1

Có, thuộc tính đính kèm rất mạnh và cho phép bạn thêm tất cả các loại hành vi. –

4

Bạn có thể đặt một xác nhận trong ràng buộc của bạn

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

Nhìn vào ví dụ này (của chương trình của tôi), bạn đặt các xác nhận bên trong ràng buộc như thế này. Với UpdateSourceTrigger bạn có thể thay đổi khi bạn ràng buộc sẽ được cập nhật (mất tập trung, trong mọi thay đổi ...)

Vâng, xác nhận là một lớp học, tôi sẽ đưa bạn một ví dụ:

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

Nói tóm lại , thực hiện công việc bên trong phương thức đó và trả về một ValidationResult mới. Tham số đầu tiên là một bool, true nếu xác thực là tốt, false nếu không. Tham số thứ hai chỉ là một thông báo cho thông tin.

Tôi nghĩ rằng đây là những điều cơ bản về xác thực hộp văn bản.

Hy vọng trợ giúp này.

EDIT: Xin lỗi, tôi không biết VB.NET nhưng tôi nghĩ rằng mã C# khá đơn giản.

+0

Tôi biết cả hai nên rất dễ dàng cho tôi để conver nó. Cảm ơn bạn, tôi sẽ thử nó đủ sớm. –

Các vấn đề liên quan