首页 > 其他分享 >WPF 输入文本检测是否为数字

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

时间:2022-09-19 17:22:17浏览次数:70  
标签:OnPropertyChanged return string System Comments WPF 文本 public 输入

 

<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));
        }
    }
}
后台代码

 

标签:OnPropertyChanged,return,string,System,Comments,WPF,文本,public,输入
From: https://www.cnblogs.com/lizhiqiang0204/p/16708367.html

相关文章