Overview
The release of Silverlight 2 Beta 1 brings us a lot of surprises from Runtime and Tools, such as supporting the framework languages Visual Basic, Visual C #, IronRuby, Ironpython, A series of new features such as JSON, Web Service, WCF, and Sockets support. The one-step learning Silverlight 2 series article takes you to Silverlight 2 development quickly.
This article is the sixth in a series of articles. It introduces the keyboard processing events in Silverlight. In Silverlight 2, The KeyDown and KeyUp events are supported.
Declare events
All event declaration processes are the same, and are registered in XAML or code.
<Canvas x:Name="LayoutRoot" Background="#46461F"> <Ellipse x:Name="ellipse" Width="120" Height="120" Fill="Orange" Canvas.Top="50" Canvas.Left="160" Stroke="White" StrokeThickness="2" KeyUp="ellipse_KeyUp" KeyDown="ellipse_KeyDown"/></Canvas>
Or register in the Code:
public partial class Page : UserControl{ public Page() { InitializeComponent(); this.ellipse.KeyUp += new KeyEventHandler(ellipse_KeyUp); this.ellipse.KeyDown += new KeyEventHandler(ellipse_KeyDown); } private void ellipse_KeyUp(object sender, KeyEventArgs e) { } private void ellipse_KeyDown(object sender, KeyEventArgs e) { }}
Use the event parameter KeyEventArgs
You can use event parameters to obtain event data, including Key, PlatformKeyCode, Handled, and Source attributes.
private void ellipse_KeyUp(object sender, KeyEventArgs e){ if (e.Key == Key.R) { //...... } else if(e.Key == Key.Ctrl && e.Key == Key.U) { //...... }}
Handled is sometimes useful in event data and can be used to determine whether an event has been processed.
Keyboard routing event
Both KeyDown and KeyUp support Event Routing, as shown in the following example.
<Canvas x:Name="LayoutRoot" Background="#46461F" KeyUp="LayoutRoot_KeyUp"> <TextBox x:Name="textbox" Width="200" Height="40" Canvas.Top="80" Canvas.Left="80"/> <Button x:Name="button" Width="100" Height="40" Canvas.Top="80" Canvas.Left="280" Background="Red" Margin="20 0 0 0" Content="Submit"/> <TextBlock x:Name="Status" Foreground="White" Text="Status" Canvas.Left="80" Canvas.Top="200"/></Canvas>
Register a KeyUp event for Canvas and write an event handler.
private void LayoutRoot_KeyDown(object sender, KeyEventArgs e){ if (e.Key != Key.Unknown) { String msg = "The key " + e.Key.ToString(); msg += " was pressed while focus was on " + (e.Source as FrameworkElement).Name; statusTextBlock.Text = msg; }}
Run the program. When the text box gets focus and t is entered
Button to get focus
Conclusion
We will give a brief introduction to Keyboard Events and hope they will be useful to you.
Next article: Learn Silverlight 2 series (7) step by step: Full Screen mode supported