-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumericTextBoxHelper.cs
More file actions
57 lines (48 loc) · 1.39 KB
/
NumericTextBoxHelper.cs
File metadata and controls
57 lines (48 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Upsilon.Apps.Passkey.GUI.WPF.Helper
{
public static class NumericTextBoxHelper
{
private static readonly Regex _regex = new("[^0-9]+"); //regex that matches disallowed text
private static bool _isTextAllowed(string text)
{
bool isValid = !_regex.IsMatch(text);
if (isValid)
{
isValid = int.TryParse(text, out _);
}
return isValid;
}
public static void TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = (TextBox)sender;
e.Handled = !_isTextAllowed(textBox.Text);
if (e.Handled)
{
textBox.Text = textBox.Text.Replace(" ", "");
}
}
public static void PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !_isTextAllowed(e.Text);
}
public static void Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
string text = (string)e.DataObject.GetData(typeof(string));
if (!_isTextAllowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
}
}