Search code examples
xamluwpuwp-xaml

How to prevent Esc key from light dismissing a popup?


I have a Popup which needs to be light dismissed when user taps an element outside the popup. By default, pressing the Esc key also triggers LightDismiss, which I would like to prevent. Instead, I'd like to handle this KeyDown event explicitly.

Handling the Tapped event in the page's root to check if user's tapped outside the popup is one solution, but since every tap in my app will go through this, I'd prefer not to take this approach.

Some pseudo-code:

<Page>
    <Grid>
        <Popup
            x:Name="FooTip"
            Opened="FooTip_Opened"
            Closed="FooTip_Closed"
            IsLightDismissEnabled="True"
            ShouldConstrainToRootBounds="True">
            <!-- Popup content here -->
        </Popup>
    </Grid>
</Page>

TLDR: FooTip should not get light dismissed when Esc key is pressed.


Solution

  • FooTip should not get light dismissed when Esc key is pressed.

    You could handle the PreviewKeyDown event for the Page like this:

    private void OnPreviewKeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Escape
            && FooTip.IsOpen)
        {
            e.Handled = true;
        }
    }