Silverlight issues: Handling KeyDown and KeyUp events
Issues
- When you attach to KeyDown / KeyUp event you get a JavaScript error AG_E_INIT_ROOTVISUAL (ErrorCode: 2101).
- KeyboardEventArgs.Key is not a standard ASCII code
Description
In Silverlight 1.1 Alpha keyboard events can only be handled on the root most Canvas. That is the reason you get Error 2101.
The Key you receive from the KeyboardEventArgs is not a standard ACII Code in this release.
Solutions
To get the root most Canvas you can iterate trough all parents of your control. The following code explains it:
FrameworkElement parent = myTextBlock.Parent as FrameworkElement;
while (parent != null)
{
if (parent.Parent != null)
parent = parent.Parent as FrameworkElement;
else
break;
}
if (parent != null)
(parent as Canvas).KeyDown +=
new KeyboardEventHandler(myTextBlock_KeyDown);
To workaround the second issue you should use this Key Enumeration to handle the actual key. But if you need to localize it – good luck