开发者

Use Enter key on keyboard as well as mouse click to bind a button to a command

I have a Silverlkight 4 application built with MVVM Light. I have various views with buttons on that are bound to commands in the viewmodels.

Everything works fine, when you click on a button开发者_JS百科, the command fires and whatever was called works.

All I want to change is instead of the user having to use to mouse to press the button to call the command I would like them to have the option of pressing return on the keyboard.

Simple I thought but at the moment I am stuck and cannot find any info of how to accomplish this. Any ideas please.


Why dont you add a KeyUp event on the control - and handle the "Enter" key in the code behind to fire off the event in the view model?

EG:

In XAML:

......... KeyUp="Control_KeyUp" />

In the CODE BEHIND:

private void Control_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if(e.Key == System.Windows.Input.Key.Enter)
        {
            GlobalViewModelLocator.ViewModel.FireControlCommand(..);
        }
    }

Where GlobalViewModelLocator refers to a static class which holds references to the view models used in the views.


Thanks for the reply Vixen. I could see how this would work. I have already sorted it by using the code behind.

In the xaml I add a keydown event to the property of the control I was in which in my case was a grid but could be a listbox, textbox or whatever.

Then in the code behind I added

private void IfEnterIsPressed(object sender, KeyEventArgs e)
{
   if (e.Key == Key.Enter)
   { 
      var vm = DataContext as ViewModel; if (vm != null) vm.MyCommand.Execute(null); 
   }            
}

This worked for me

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜