Binding KeyDown Event Silverlight

喜欢而已 提交于 2019-12-25 03:30:34

问题


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();  
         } }

回答1:


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



来源:https://stackoverflow.com/questions/12714727/binding-keydown-event-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!