只須要兩步:正則表達式
1.禁掉輸入法:spa
<Window x:Class="WpfModelViewApplication1.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
Title="Main Window" Height="400" Width="800">
<Grid x:Name="grid1">
<TextBox x:Name="tb" Width="100" HorizontalAlignment="Right" Margin="0,164,122,128" input:InputMethod.IsInputMethodEnabled="False"/>
</Grid>
</Window>
第二步 採用正則表達式:code
<Window x:Class="WpfModelViewApplication1.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
Title="Main Window" Height="400" Width="800">xml
<Grid x:Name="grid1">
<TextBox x:Name="tb" Width="100" HorizontalAlignment="Right" Margin="0,164,122,128" PreviewTextInput
=
"tb_PreviewTextInput"
input:InputMethod.IsInputMethodEnabled="False"/>
</Grid>blog
</Window>input
cs後臺代碼:string
//using System.Text.RegularExpressions; private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex re = new Regex("[^0-9.-]+"); e.Handled = re.IsMatch(e.Text); }