WPF MVVM KeyBinding not being recognized right away and not always working

后端 未结 3 1008
[愿得一人]
[愿得一人] 2021-01-13 23:32

For whatever reason, the KeyBindings for my UserControl aren\'t working as soon as my WPF Application loads. They do work after I press a button on the form but not when I s

相关标签:
3条回答
  • 2021-01-13 23:45

    I ran into the same issue. I followed up on the focus issue. I found that when I set my focus to a button inside of my form, the commands started working. If my focus item gets deleted and not redirected (such as deleting the last item from a listbox), then none of my commands work.

    I manually reset my keyboard focus to a default item in the cases that were leaving my focus ina weird state causing my commands to break. In my case, that was the page loaded event and the delete command (when there were no more items in my list box).

    0 讨论(0)
  • 2021-01-13 23:54

    Have you verified that the control actually has focus when it loads by using Mole? It could be that whatever your parent control is keeps focus until your buttons are selected manually. As for the Enter keys, it sounds as if they are probably selecting the last clicked button since it would still have focus instead of firing your commands.

    You may need to look at your commands as I'm not sure the declarations are set up correctly. For KeyBindings, your command should be referenced in XAML as a CommandReference, like this article describes.

    0 讨论(0)
  • 2021-01-14 00:01

    I'm not sure if this fully answers your question, but most of my keybinding / focus questions are solved by setting Focusable=True on your user control, and then in the code behind, call Focus() on the view's load event.

        <UserControl ....
             Focusable="True"
             Loaded="Act_Loaded" >
    
        private void Act_Loaded(object sender, RoutedEventArgs e)
        {
            Focus();
        }
    
    0 讨论(0)
提交回复
热议问题