开发者

MVVM Handle all un handled keystrokes on ViewModel

开发者 https://www.devze.com 2023-01-27 20:40 出处:网络
I don\'t know if this is a good way to work but i need to handle all unhandled keystrokes on my ViewModel so my idea was to use a Behavior on my ShellView that would relay all unhandled keystrokes to

I don't know if this is a good way to work but i need to handle all unhandled keystrokes on my ViewModel so my idea was to use a Behavior on my ShellView that would relay all unhandled keystrokes to the ViewModel..

But the problem is how do i get all unhandled key presses?

Here is my first try to just catch them

Public Class ForwardKeyBehavior
    Inherits Behavior(Of DependencyObject)

    Protected Overrides Sub OnAttached()
        Keyboard.AddKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        Keyboard.AddPreviewKeyDownHandler(Me.AssociatedObject, AddressOf OnPreviewKeyPressed)
        MyBase.OnAttached()
    End Sub

    Protected Overrides Sub OnDetaching()
        Keyboard.RemoveKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        MyBase.OnDetaching()
    End Sub

    Private Sub OnPrevie开发者_如何学PythonwKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)

    End Sub

    Private Sub OnKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)
        If (Not e.Handled) Then
            Trace.Write(e.Key.ToString())
        End If
    End Sub

End Class

But it seems that e.Handled always is false so what am i missing even if i press a key in a textbox?


You set e.Handled = True to tell the program that the event has been handled and to stop executing any other functions that are registered to that event.

For example, if you hook up two methods to the KeyPressed event, and the first one sets e.Handled = True, then the 2nd event will never get executed.

I am guessing that all you really need to do is make sure your UnhandledKeyPressedEvent comes last in the event sequence, and that any other KeyPressed events set e.Handled = True to prevent the UnhandledKeyPressedEvent from executing.


Check out MSDN

Pay attention to "The Concept of Handled" section, especially the handledEventsToo part.

0

精彩评论

暂无评论...
验证码 换一张
取 消