博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WPF TextBox限制只能输入数字的两种方法
阅读量:4033 次
发布时间:2019-05-24

本文共 1989 字,大约阅读时间需要 6 分钟。

文本框中只能输入数字,一个常见的功能喽,今天就来看看如何实现它~

下面就看看代码

思路都写在xaml里面了,

MainWindow.xaml:

MainWindow.cs:

using System.Text.RegularExpressions;using System.Windows;namespace wpfcore{    public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            DataContext = this;        }        private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)        {            e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);        }    }}

第二种方法:

新建一个TextBoxAttachedProperties.cs文件,定义附加属性:

using System.Text.RegularExpressions;using System.Windows;using System.Windows.Controls;using System.Windows.Input;namespace wpfcore{    public class TextBoxAttachedProperties    {        public static bool GetIsOnlyNumber(DependencyObject obj)        {            return (bool)obj.GetValue(IsOnlyNumberProperty);        }        public static void SetIsOnlyNumber(DependencyObject obj, bool value)        {            obj.SetValue(IsOnlyNumberProperty, value);        }        public static readonly DependencyProperty IsOnlyNumberProperty =            DependencyProperty.RegisterAttached("IsOnlyNumber", typeof(bool), typeof(TextBox), new PropertyMetadata(false,                (s, e) =>                {                    if (s is TextBox textBox)                    {                        textBox.SetValue(InputMethod.IsInputMethodEnabledProperty, !(bool)e.NewValue);                        textBox.PreviewTextInput -= TxtInput;                        if (!(bool)e.NewValue)                        {                            textBox.PreviewTextInput += TxtInput;                        }                    }                }));        private static void TxtInput(object sender, System.Windows.Input.TextCompositionEventArgs e)        {            e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);        }    }}

ok,结束喽

如果喜欢,点个赞呗~

转载地址:http://eeydi.baihongyu.com/

你可能感兴趣的文章
linux kconfig配置
查看>>
linux不同模块completion通信
查看>>
linux printf获得时间戳
查看>>
C语言位扩展
查看>>
linux dump_backtrace
查看>>
linux irqdebug
查看>>
git 常用命令
查看>>
linux位操作API
查看>>
uboot.lds文件分析
查看>>
uboot start.s文件分析
查看>>
没有路由器的情况下,开发板,虚拟机Ubuntu,win10主机,三者也可以ping通
查看>>
本地服务方式搭建etcd集群
查看>>
安装k8s Master高可用集群
查看>>
忽略图片透明区域的事件(Flex)
查看>>
忽略图片透明区域的事件(Flex)
查看>>
AS3 Flex基础知识100条
查看>>
Flex动态获取flash资源库文件
查看>>
flex中设置Label标签文字的自动换行
查看>>
Flex 中的元数据标签
查看>>
flex4 中创建自定义弹出窗口
查看>>