65.9K
CodeProject is changing. Read more.
Home

How Do I Make a textbox Class Which Only Takes Numeric Data in WPF Application

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (3 votes)

Aug 3, 2016

CPOL
viewsIcon

6540

downloadIcon

48

Making a TextBoxClass allows only numeric data

Introduction

Firstly, we try to create new WPF application. And add a new class. In my example class, the name is Class1.

Background

textBox.PreviewTextInput += 
new System.Windows.Input.TextCompositionEventHandler(Class1.PreviewTextInput);

Each textBox using Class1, it will have numerical property.

Using the Code

In MainWindow (WPF page), I added my code in constructor. But you can add where you need this.

WPF Page

public MainWindow()
        {
            InitializeComponent();
            textBox.Text = "";
            textBox.PreviewTextInput += 
            new System.Windows.Input.TextCompositionEventHandler(Class1.PreviewTextInput);
        }

Class

 public static void PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            bool approvedDecimalPoint = false;

            if (e.Text == ".")
            {
                if (!((TextBox)sender).Text.Contains("."))
                    approvedDecimalPoint = true;
            }

            if (!(char.IsDigit(e.Text, e.Text.Length - 1) || approvedDecimalPoint))
                e.Handled = true;
        }

Points of Interest

Add libraries.

using System.Windows.Controls;
using System.Windows.Input;

History

  • 3rd August, 2016: Initial version