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