路由事件的類型:具體參考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事件