Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept only integers in a WPF textbox [duplicate]

Tags:

c#

wpf

xaml

Do you know how to restrict user input in textbox, this textbox only accepts integer? By the way I'm developing for Windows 8. I've tried what I searched from SO and from Google but it's not working,

like image 481
Dunkey Avatar asked Feb 11 '13 14:02

Dunkey


1 Answers

If you don't want to download the WPF ToolKit (which has both the IntegerUpDown control or a MaskedTextBox), you can implement it yourself as adapted from this article on Masked TextBox In WPF using the UIElement.PreviewTextInput and DataObject.Pasting events.

Here's what you would put in your window:

<Window x:Class="WpfApp1.MainWindow" Title="MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Orientation="Vertical" Width="100" Height="100"  HorizontalAlignment="Left" VerticalAlignment="Top">

        <TextBlock Name="NumericLabel1"  Text="Enter Value:"  />
        <TextBox   Name="NumericInput1" 
                   PreviewTextInput="MaskNumericInput" 
                   DataObject.Pasting="MaskNumericPaste"  />
    </StackPanel>
</Window>

And then implement the C# in your codebehind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MaskNumericInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !TextIsNumeric(e.Text);
    }

    private void MaskNumericPaste(object sender, DataObjectPastingEventArgs e)
    {
        if (e.DataObject.GetDataPresent(typeof(string)))
        {
            string input = (string)e.DataObject.GetData(typeof(string));
            if (!TextIsNumeric(input)) e.CancelCommand();
        }
        else
        {
            e.CancelCommand();
        }
    }

    private bool TextIsNumeric(string input)
    {
        return input.All(c => Char.IsDigit(c) || Char.IsControl(c));
    }
}
like image 160
KyleMit Avatar answered Oct 31 '22 21:10

KyleMit