天天看點

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);
}
           

簡簡單單的兩步這就完成了

WPF

繼續閱讀