restrict input for numeric controls

allow input dots
This commit is contained in:
Oleksandr Bezdieniezhnykh
2025-10-01 20:12:30 +03:00
parent 5e226d422d
commit 51248edbd3
2 changed files with 28 additions and 1 deletions
+3 -1
View File
@@ -23,8 +23,10 @@
TextAlignment="Right"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
Text="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type local:NumericUpDown}}}"
Text="{Binding Value, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type local:NumericUpDown}}}"
LostFocus="NudTextBox_OnLostFocus"
PreviewTextInput="NudTextBox_OnPreviewTextInput"
DataObject.Pasting="NudTextBox_OnPasting"
/>
<RepeatButton
Name="NudButtonUp"
@@ -1,6 +1,8 @@
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Azaion.Common.Controls;
@@ -98,4 +100,27 @@ public partial class NumericUpDown : UserControl
NudTextBox.SelectionStart = NudTextBox.Text.Length;
}
private void NudTextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var regex = new Regex("[^0-9.]+");
e.Handled = regex.IsMatch(e.Text);
}
private void NudTextBox_OnPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
var text = (string)e.DataObject.GetData(typeof(string));
var regex = new Regex("[^0-9.]+");
if (regex.IsMatch(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
}