Summary 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. The process of declaring all events of an event is the same. It is registered in XAML or in 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) { }}
You can use the event parameter keyeventargs to obtain event data using the event parameter. The attributes available include key, platformkeycode, handled, and source.
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 keydown and keyup both support routing events, 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 the focus and enter t, the button gets the focus. The Keyboard Events are briefly described here. I hope it will be useful to you.
This article is from the "terrylee technology column" blog, please be sure to keep this source http://terrylee.blog.51cto.com/342737/67225
This article is from 51cto. com technical blog