Home > front end >  key strokes events dont execute in C# WPF
key strokes events dont execute in C# WPF

Time:01-05

I'm using WPF MVVM pattern with Prism im trying to bind keybind to some command

----View---

<Canvas Background="Red" Grid.Row="1">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="PreviewKeyDown">
                    <prism:InvokeCommandAction Command="{Binding KeyDownCmd}"/>
                </i:EventTrigger>
                <i:EventTrigger EventName="KeyDown">
                    <prism:InvokeCommandAction Command="{Binding KeyUpCmd}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>           
        </Canvas>

----View Model----

       #region Commands
        public DelegateCommand<KeyEventArgs> KeyDownCmd { get; private set; }
        public DelegateCommand<KeyEventArgs> KeyUpCmd { get; private set; }
        
        #endregion

        #region Ctor
        public GameViewModel()
        {
            KeyDownCmd = new DelegateCommand<KeyEventArgs>(KeyDownExecute);
            KeyUpCmd = new DelegateCommand<KeyEventArgs>(KeyUpExecute);            
        } 

        private void KeyUpExecute(KeyEventArgs obj)
        {
           //some code here
        }

        private void KeyDownExecute(KeyEventArgs obj)
        {
             //some code here
        }

i also tried to bind to code-behind like this KeyDown="Canvas_KeyDown" and nothing

tried to use PreviewKeyDown /PreviewKeyUp and nothing

also tried to bind the key command to the gird above the canvas and to the userControl and nothing

P.S im navigating between pages with viewInjection as described here

CodePudding user response:

A Canvas doesn't raise any key stroke events unless it's Focusable and focused.

You can make it focusable by setting the property in the XAML but you still have to focus it at some point, for example when it's clicked:

private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Canvas canvas = (Canvas)sender;
    Keyboard.Focus(canvas);
}

XAML:

<Canvas Focusable="True" Background="Red"
        PreviewKeyDown="Canvas_PreviewKeyDown"
        MouseLeftButtonDown="Canvas_MouseLeftButtonDown">
    ...
</Canvas>

You should probably reconsider your approach and handle the PreviewKeyDown of a parent element or a focusable child element of the Canvas instead.

  •  Tags:  
  • Related