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,
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:
<!-- language: lang-xml --> <pre><code><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" <b>PreviewTextInput="MaskNumericInput"</b> <b>DataObject.Pasting="MaskNumericPaste"</b> /> </StackPanel> </Window></code></pre>And then implement the C# in your codebehind:
<!-- language: lang-cs --> <pre><code>public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } <b>private void MaskNumericInput(object sender, TextCompositionEventArgs e)</b> { e.Handled = !TextIsNumeric(e.Text); } <b>private void MaskNumericPaste(object sender, DataObjectPastingEventArgs e)</b> { if (e.DataObject.GetDataPresent(typeof(string))) { string input = (string)e.DataObject.GetData(typeof(string)); if (!TextIsNumeric(input)) e.CancelCommand(); } else { e.CancelCommand(); } } <b>private bool TextIsNumeric(string input)</b> { return input.All(c => Char.IsDigit(c) || Char.IsControl(c)); } }</code></pre>