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

TextBoxの添付プロパティを使用してのみ入力を数値に制限できます。添付されたプロパティを(別の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

私はそれを試みます。 私はそれに事実上何かを加えることができると想像します。たとえば、内部のテキストの最大長さ、これも私が持っていた別の問題です。 –

+0

浮動小数点の最大長(整数部分の最大10進数と最大数) –

+1

はい、添付プロパティは非常に強力で、すべてのタイプの動作を追加することができます。 –

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です。 2番目のパラメータは情報のためのメッセージです。

私はこれがテキストボックス検証の基本だと思います。

このヘルプが必要です。

編集:申し訳ありませんが、VB.NETはわかりませんが、C#コードはかなり簡単だと思います。

+0

私が知っている、両方の私はそれをCONVERするので、それは簡単です。 ありがとう、私はすぐにそれを試してみます。 –

関連する問題