WPF 输入文本检测是否为数字

 

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel Orientation="Horizontal">
        <TextBox Text="{Binding InTexts, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="120" VerticalAlignment="Top"/>
        <TextBlock Text="{Binding Comments}" Foreground="Red" />
    </StackPanel>
</Window>
前台代码
using System.ComponentModel;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }
        private string _inTexts;
        public string InTexts
        {
            get { return _inTexts; }
            set
            {
                _inTexts = value;
                OnPropertyChanged("InTexts");
                if (isNumberic(InTexts) == false)
                    Comments = "请输入数字";
                else
                    Comments = null;
            }
        }
        private string _comments;
        public string Comments
        {
            get { return _comments; }
            set
            {
                _comments = value; OnPropertyChanged("Comments");
            }
        }
        protected bool isNumberic(string message)
        {
            System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$");
            if (rex.IsMatch(message))
                return true;
            else
                return false;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string info)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}
后台代码

 

posted @ 2022-09-19 17:13  阿坦  阅读(148)  评论(0)    收藏  举报