I would like to make a regular expression that limits the textboxes I have to negative real numbers. Unfortunately, the best I have been able to do is to limit the text box to numbers only. I have tried several "working" examples from around the web, but none of them worked for me. Here is my code based on my book and how I would think I should build the regular expression.
- using System.Text.RegularExpressions;
- using System.Windows;
- using System.Windows.Input;
-
- namespace WPF_Test_Unit
- {
-
-
-
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- this.SizeToContent = SizeToContent.WidthAndHeight;
- }
-
- private void CheckForNumber(object sender, TextCompositionEventArgs e)
- {
- Regex regex = new Regex(@"\-?\d+\.?\d+");
- e.Handled = !regex.IsMatch(e.Text);
- }
- }
-
- }
My idea is that I would need 0 or 1 negative sign "-", then one or more digits, an optional decimal "." and then one or more digits trailing the decimal point.
Below is the XAML that uses the function.
- <TextBox Grid.Row="3" Grid.Column="1" VerticalAlignment="Center" PreviewTextInput="CheckForNumber" HorizontalAlignment="Center" FontSize="20" Width="170" Height="40" />
I have tried many combinations of regular expressions, but the only results I can get with preventing characters in the textbox a numbers-only situation. Trying to remove (or allow) other characters seems not to work.