Search code examples
silverlightcaliburn.microkey-bindings

Binding KeyDown Event Silverlight


I am attempting to have a key binding cause an event within the view model. I have been search for a while and have not come across any solutions that have worked thus far, unfortunately.

This is what I am basically attempting to implement:

<i:Interaction.Triggers>  
    <i:EventTrigger EventName="createNew">  
       <cal:ActionMessage MethodName="newCustomer" />  
    </i:EventTrigger>  
</i:Interaction.Triggers>

I am wanting a way to provide a "hotkey" to allow the user to implement a newCustomer event within the view model. So far it won't even reach into the view model. If I attach the EventName="KeyDown" it works wonderfully if any key is pressed, but I am attempting to target a single key.

I will add that the code behind in the view model looks like this.

public void createNew(object sender, KeyEventArgs e)
     { if (e.Key == Key.F9)
         {
             addCustomer();  
         } }

Solution

  • Not too sure what control you are using, but for example purposes I'll use a text-box... Not entirely sure if this will help even, but I hope it does:

    The View:

    <TextBox x:Name="MyTextBox" TextAlignment="Left" FontSize="10" Width="240" cal:Message.Attach="[Event KeyUp]=[Action ExecuteAction($executionContext)]"/>
    

    The ViewModel:
    * For example purposes I'll use "Enter" as the single key on which you want the actions performed.

    public void ExecuteAction(ActionExecutionContext context)
        {
            var eventArgs = (KeyEventArgs)context.EventArgs;
            if (eventArgs.Key != Key.Enter) return; 
            //Execute Actions...
        }
    

    This ought to fire code on each key-press on the control you want, if the key is not equal to whatever you specify, it won't do anything...

    If I'm waaay off, maybe I just don't understand the issue correctly :D