关于正则表达式的使用一例。在Textbox 对话框内限制只能输入数字,如果输入出错,则清空内容。
在这个例子中,我们使用正则表达式来限制输入的内容,在使用之前,必须先要引入一个命名空间
using System.Text.RegularExpressions;
我们 XAML 文档中,指定事件订阅
1 <Grid>
2 <TextBox Height="23" HorizontalAlignment="Left" Margin="11,8,0,0" Name="textBox1" VerticalAlignment="Top" Width="40" TextChanged ="textBox1_DataContextChanged" />
3 //TextChanged 就是订阅的事件
4 <TextBox Height="23" HorizontalAlignment="Left" Margin="64,8,0,0" Name="textBox2" VerticalAlignment="Top" Width="40" TextChanged ="textBox1_DataContextChanged" />
5 //TextChanged 就是订阅的事件
6 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,7,0,0" Name="textBox3" VerticalAlignment="Top" Width="40"/>
7 <Button Content="计算" Height="23" HorizontalAlignment="Left" Margin="174,8,0,0" Name="button1" VerticalAlignment="Top" Width="40" Click="button1_Click" />
8 <Label Content="+" Height="28" HorizontalAlignment="Left" Margin="47,5,0,0" Name="label1" VerticalAlignment="Top" />
9 <Label Content="=" Height="28" HorizontalAlignment="Left" Margin="101,5,0,0" Name="label2" VerticalAlignment="Top" />
10 </Grid>
2 <TextBox Height="23" HorizontalAlignment="Left" Margin="11,8,0,0" Name="textBox1" VerticalAlignment="Top" Width="40" TextChanged ="textBox1_DataContextChanged" />
3 //TextChanged 就是订阅的事件
4 <TextBox Height="23" HorizontalAlignment="Left" Margin="64,8,0,0" Name="textBox2" VerticalAlignment="Top" Width="40" TextChanged ="textBox1_DataContextChanged" />
5 //TextChanged 就是订阅的事件
6 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,7,0,0" Name="textBox3" VerticalAlignment="Top" Width="40"/>
7 <Button Content="计算" Height="23" HorizontalAlignment="Left" Margin="174,8,0,0" Name="button1" VerticalAlignment="Top" Width="40" Click="button1_Click" />
8 <Label Content="+" Height="28" HorizontalAlignment="Left" Margin="47,5,0,0" Name="label1" VerticalAlignment="Top" />
9 <Label Content="=" Height="28" HorizontalAlignment="Left" Margin="101,5,0,0" Name="label2" VerticalAlignment="Top" />
10 </Grid>
再来看一个 下面这个CS文件,
private void textBox1_DataContextChanged(object sender, TextChangedEventArgs e)
{
Regex rgx = new Regex(@"^\d+$");
string ss = (sender as TextBox).Text;
if (!rgx.IsMatch(ss))
{
(sender as TextBox).Text = "";
}
}
{
Regex rgx = new Regex(@"^\d+$");
string ss = (sender as TextBox).Text;
if (!rgx.IsMatch(ss))
{
(sender as TextBox).Text = "";
}
}
这里的正则表达式是 “^\d+$” 前面的 @ 起到 按原文 转义字符,如果不加,那正则表达式就错了。