0

i Have a Text box whose Text is bind with string data type property. but i need to enter only numeric values in this Text box.

Its looks weird, but this is one of requirement, same Text box can accept string and numeric values. I can not take two Text box and handle this with Visibility of Text boxes.

1
  • Did you tried coding for textbox's onkeydown event and handle the control for relevant values? Commented Aug 2, 2013 at 8:01

3 Answers 3

1

You can do this pretty nicely using an AttachedProperty:

I have a class called TextBoxProperties with my attached properties for TextBox controls:

#region IsNumericOnly

/// <summary>
/// Provides the ability to restrict the text input of the TextBox control to only allow numeric values to be entered.
/// </summary>
public static readonly DependencyProperty IsNumericOnlyProperty = DependencyProperty.RegisterAttached("IsNumericOnly", typeof(bool), typeof(TextBoxProperties), new UIPropertyMetadata(default(bool), OnIsNumericOnlyChanged));

/// <summary>
/// Gets the value of the IsNumericOnly property.
/// </summary>
/// <param name="dependencyObject">The DependencyObject to return the IsNumericOnly property value from.</param>
/// <returns>The value of the IsNumericOnly property.</returns>
public static bool GetIsNumericOnly(DependencyObject dependencyObject)
{
    return (bool)dependencyObject.GetValue(IsNumericOnlyProperty);
}

/// <summary>
/// Sets the value of the IsNumericOnly property.
/// </summary>
/// <param name="dependencyObject">The DependencyObject to set the IsNumericOnly property value of.</param>
/// <param name="value">The value to be assigned to the IsNumericOnly property.</param>
public static void SetIsNumericOnly(DependencyObject dependencyObject, bool value)
{
    dependencyObject.SetValue(IsNumericOnlyProperty, value);
}

/// <summary>
/// Adds key listening event handlers to the TextBox object to prevent non numeric key strokes from being accepted if the IsNumericOnly property value is true, or removes them otherwise.
/// </summary>
/// <param name="dependencyObject">The TextBox object.</param>
/// <param name="dependencyPropertyChangedEventArgs">The DependencyPropertyChangedEventArgs object containing event specific information.</param>
public static void OnIsNumericOnlyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
    TextBox textBox = dependencyObject as TextBox;
    if (textBox != null)
    {
        bool newIsNumericOnlyValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
        TextCompositionEventHandler textBox_PreviewTextInput = new TextCompositionEventHandler((s, e) => e.Handled = !e.Text.All(c => Char.IsNumber(c) && c != ' '));
        KeyEventHandler textBox_PreviewKeyDown = new KeyEventHandler((s, e) => e.Handled = e.Key == Key.Space);
        if (newIsNumericOnlyValue)
        {
            textBox.PreviewTextInput += textBox_PreviewTextInput;
            textBox.PreviewKeyDown += textBox_PreviewKeyDown;
        }
        else
        {
            textBox.PreviewTextInput -= textBox_PreviewTextInput;
            textBox.PreviewKeyDown -= textBox_PreviewKeyDown;
        }
    }
}

#endregion

It is used like so:

Add XML namespace:

xmlns:Attached="clr-namespace:Fully.Qualified.Namespace"

Then XAML:

<TextBox Text="{Binding YourString}" Attached:TextBoxProperties.IsNumericOnly="True" />

You can apply this to any Textbox and it will not allow any non-numerical numbers to be entered.

Sign up to request clarification or add additional context in comments.

7 Comments

It's not complicated... unless you think that an Attached Property is complicated. This is a standard Attached Property with about 10 lines of code... hardly complicated. And the reason why? Reusability. We OO developers like to reuse code.
dont forget to handle copy&paste and Whitespace
Do OO developers like dirty initalizing of anonymous event handlers? I suggest ValidationRule for this situation. You can reuse ValidationRules too.
@ninja pls post your ValidationRule solution as answer
Why should I? I think Amit Sch..asdf is very well capable to do that on its own.
|
1

If you need only numeric values then do following.

  1. Inside your property setter validate the new value if all chars are numbers.
  2. If so then set the new value
  3. If not so don't do anything.

Binding uses getters and setters. Once binding updates setter of a property it calls its getter. When you enter text in TextBox and inside your setter you dont set the value. The text wont get entered.

Alternative would be using the ValidationRules.

Comments

1

you can do this

<TextBox Text="{Binding Path=Amount}">            
    <i:Interaction.Behaviors>                
        <Behaviors:TextBoxInputBehavior InputMode="DigitInput" />
    </i:Interaction.Behaviors>
</TextBox>

i post the code these days here: Validate decimal numbers in a WPF TextBox

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.