简体   繁体   中英

IsDefault for WPF button - overriding everything

Is there an option to force Enter to be the main key on certain view? What I want to achieve is whenever I click "Enter" key I want to invoke button which has "IsDefault" property set to true, no matter what is focused.

One possibility would be to intercept the RoutedEvent before it gets to the controls that try to react to it:

Connect to the PreviewKeyDown event as far up the visual tree as you want to catch it. React to it there accordingly if the enter key was pressed, eg run the same code as in your button, and then set in the eventargs Handled to true .

private void previewKeyDownHandler(object sender, KeyEventArgs e)
{
    if(e.Key == Key.Enter || e.Key == Key.Return)
    {
        e.Handled = true;
        //Do your stuff
    }
}

The Preview events are part of the RoutedEvent system in WPF. The 2 mechanisms are called Tunneling and Bubbling. Here you can read more on that .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM