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:
<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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With