文本框中只能输入数字,一个常见的功能喽,今天就来看看如何实现它~
下面就看看代码
思路都写在xaml里面了,
MainWindow.xaml:
<Window x:Class="wpfcore.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:wpfcore" xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"mc:Ignorable="d"Background="#2D2D30"SnapsToDevicePixels="True"FontSize="18"UseLayoutRounding="True"Title="MainWindow" Width="820" Height="340"><StackPanel><!--第一种方法,直接设置禁用输入法,并添加PreviewTextInput事件,如果不满足条件,就禁止输入--><TextBox InputMethod.IsInputMethodEnabled="False" PreviewTextInput="TextBox_PreviewTextInput" Margin="10"/><!--第二种方法,写一个附加属性,在属性改变时,给textbox添加上相应事件,这个写完后,复用时就方便喽--><TextBox local:TextBoxAttachedProperties.IsOnlyNumber="true" Margin="10"/></StackPanel>
</Window>
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,结束喽
如果喜欢,点个赞呗~