本文共 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/