using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox t = sender as TextBox;
Regex re = new Regex("[0-9]+");
if(re.IsMatch(e.Text) && t.Text.Length < 9)
{
e.Handled = false;
}else
{
e.Handled = true;
}
}
}
}
<Window x:Class="WpfApp1.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:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
mc:Ignorable="d"
Title="MainWindow" SizeToContent="WidthAndHeight">
<StackPanel>
<TextBox Height="30" Width="200" PreviewTextInput="tb_PreviewTextInput" input:InputLanguageManager.InputLanguage="ja-jp" input:InputMethod.IsInputMethodEnabled="False"/>
</StackPanel>
</Window>
第二种 更加简单的方法实现