路由事件的类型:具体参考http://www.javashuo.com/article/p-yyqdpcto-dt.htmlhtml
当用户按下一个键,就会触发一系列的事件,这里按顺序依次列出公共的事件:this
上面是一些公共的事件,不一样控件可能还有一些本身特有的事件,为了避免冲突,还会将上面的致使冲突的事件挂起。例如TextBox控件拥有TextChanged事件,而挂起了TextInpute事件(不会触发)。所以,建议用Preview开头的事件spa
通常按键都会触发Preview开头的事件,除了特殊按键,如空格键、方向键、Alt键等非输入键。.net
案例:经过PreviewTextInput判断输入是否合法,不合法则阻止输入code
XAML代码:htm
<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <DockPanel Grid.Row="0"> <TextBlock Text="请输入数字:" Margin="3"/> <TextBox PreviewTextInput="TextBox_PreviewTextInput" /> </DockPanel> <ListBox x:Name="listBox" Grid.Row="1" Margin="5"/> <Button x:Name="Clear" Content="清除" Grid.Row="2" HorizontalAlignment="Right" Margin="5" Padding="3" Click="Clear_Click"/> </Grid>
CS代码:blog
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { string message = "Event:" + e.RoutedEvent + " " + "Text:" + e.Text; this.listBox.Items.Add(message); long num = 0; if (!long.TryParse(e.Text, out num)) { MessageBox.Show(e.Text + "键不是数字"); e.Handled = true; } } private void Clear_Click(object sender, RoutedEventArgs e) { this.listBox.Items.Clear(); }
关于TextBlock和Label的比较,参考http://www.javashuo.com/article/p-veepncil-ec.html事件