WPF

2009-08-28 28 views
10

'daki metin kutusunda doğrulama Şu anda bir WPF uygulaması üzerinde çalışıyorum, bunun içinde yalnızca sayısal girdilere sahip olabilen bir TextBox olmasını istiyorum. Odağı kaybettiğimde ve içeriğin sayısal olmasını engellediğimde içeriğini doğrulayabileceğimi biliyorum, ancak diğer Windows Form uygulamalarında, sayısal olarak yazılanlar dışındaki herhangi bir girişi tamamen engellemek için kullanıyoruz. Ayrıca, bu kodu birçok yerde referans vermek için ayrı bir dll'ye koymak için kullanırız. İşte WPF

WPF 2008 yılında kodu kullanmıyor:

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 eşdeğer yolu var mı? Eğer bu tarz bir tarzda olursa olsun, ama WPF için yeniyim. Bu yüzden stil yapabildikleri veya yapamayacakları için biraz belirsiz.

cevap

23

Girdi, yalnızca TextBox'ta ekli bir özellik kullanarak sayılarla kısıtlayabilirsiniz. Ekli özelliği bir kez tanımlayın (ayrı bir dll'de bile) ve herhangi bir TextBox'ta kullanın. İşte ekli özelliktir:

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

Bunu deneyeceğim. Neredeyse böyle bir şey ekleyebileceğimi hayal ediyorum. Örneğin, içindeki metnin maksimum uzunluğu, ki benim de başka bir sorunum. –

+0

Unutmayın, bu bir kayan sayının maksimum uzunluğu (tamsayı parçasının maksimum ondalık sayısı ve maksimum sayısı) –

+1

Evet, ekli özellikler çok güçlüdür ve her türlü davranışı eklemenize izin verilir. –

4

Sen senin (benim programın) Bu örneğe

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

bak bağlayıcı bir doğrulama koyabilirsiniz, böyle bağlayıcı içine doğrulama koydu. Kısacası

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

: Eğer güncellenecektir bağlanma sırasında UpdateSourceTrigger ile

Eh, doğrulama bir sınıftır (kayıp odak ... her değişimde,) değiştirebilirsiniz, sana bir örnek verecek , bu yöntemdeki işi yapın ve yeni bir ValidationResult döndürün. İlk parametre bir doğrulamadır, doğrulama iyise true, yanlış ise yanlıştır. İkinci parametre sadece bilgi için bir mesajdır.

Bu, metin kutusu doğrulamanın temelleri olduğunu düşünüyorum.

Bu yardımın umarım.

DÜZENLEME: Üzgünüm, VB.NET'I bilmiyorum ama C# kodunun oldukça basit olduğunu düşünüyorum.

+0

ben hem bana bunu conver için kolay yüzden biliyorum:

İşte
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; } } } 

o (kendi ad ile "kontrolleri" yerine) kullanmak için nasıl. Teşekkür ederim, birazdan deneyeceğim. –