Question

I have been attempting to handle the KeyDown event of a UserControl (page) in my Silverlight application, but there seems to be some strange behaviour on the part of Silverlight user input functionality. The event is not getting raised under any circumstance. I have even tried attaching the event handler to each container control within the UserControl, but still with no luck. Indeed, the Silverlight user input "event routing" system is quite novel and seems rather strange to me, so perhaps it is just a misunderstanding on my part, though I have rather clueless about how to proceed.

The following code is a template of the particular page with which I am testing.

<UserControl x:Class="MyNamespace.CreditsPage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             KeyDown="UserControl_KeyDown">
    <Grid x:Name="LayoutRoot">
        <Border>
            <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical">
                <TextBlock TextAlignment="Center">
                A line of text.<LineBreak />
                <LineBreak />
                A line of text.<LineBreak />
                <LineBreak />
                A line of text.<LineBreak />
                <LineBreak />
                A line of text.<LineBreak />
                </TextBlock>
            </StackPanel>
        </Border>
    </Grid>
</UserControl>

In WPF, the obvious solution for such an issue would be to handle the PreviewKeyDown event, but unfortunately this is not available in Silverlight 2. Any ideas would be welcome (and a short explanation of why Silverlight event routing is behaving as it is).

Was it helpful?

Solution

You can manage the user input from the main UIElement : Application.Current.RootVisual

Application.Current.RootVisual.KeyDown += Application_KeyDown

Then you can handle in the Application_KeyDown method all user inputs from the keyboard.

You can also look at this issue : Handling KeyDown event in a Canvas

OTHER TIPS

I tried the xaml that you provided and did not have a problem handing the KeyDown event.

One thing that could be causing it: the Silverlight plugin will only see input events if it is focused. So try and click on the Silverlight content in the browser to give it input focus before pressing the keys.

Let me know if that solves your problem or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top