WPF 文本框中只能输入数字

方法还是很简单的基本上就是分为两步:

第一步:禁用输入法

在TextBox中添加属性  InputMethod.IsInputMethodEnabled="False"  就像下面这样

<TextBox InputMethod.IsInputMethodEnabled="False" Opacity="1" FontSize="14"
 Background="#b6ea7b" Foreground="#FF898585" x:Name="restTime" 
HorizontalAlignment="Left" Margin="274,81,0,299" TextWrapping="Wrap" Text="5"
 Width="49" VerticalContentAlignment="Center" BorderBrush="{x:Null}" MaxLength="2" 
PreviewTextInput="restTime_PreviewTextInput" Height="20"/>

第二步:添加正则表达式

在控件中添加  PreviewTextInput="rlimitnumber"事件

/// <summary>
/// 限制只能输入数字
/// </summary>
/// <param name="e"></param>
public void limitnumber(object sender, TextCompositionEventArgs e)
{   
 Regex re = new Regex("[^0-9]+");   
 e.Handled = re.IsMatch(e.Text);
}

简简单单的两步这就完成了

转载
https://blog.csdn.net/chenguanghan123/article/details/88028431

猜你喜欢

转载自blog.csdn.net/qq_28368039/article/details/88048569