In WPF we don’t have keypress event, generally people used keypress event in windows forms application to validate text input. Now in this example I have showed how you can validate input from textbox using PreviewTextInput event. In this example I validated input to accept float values, you can use this to validate integer or any other number type validation.
Code used in example is:
XAML:
<Window x:Class="TestApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Width="400" Height="50" PreviewTextInput="TextBox_PreviewTextInput" />
</Grid>
</Window>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestApplication {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow: Window {
public MainWindow() {
InitializeComponent();
}
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) {
if (e.Text != "." && IsNumber(e.Text) == false) {
e.Handled = true;
} else if (e.Text == ".") {
if (((TextBox) sender).Text.IndexOf(e.Text) > -1) {
e.Handled = true;
}
}
}
private bool IsNumber(string Text) {
int output;
return int.TryParse(Text, out output);
}
}
}