The current Silverlight application that I’m building has a Login view. One of the things that bugged me when I started using the application is that you would have to click the Login button after typing your password. I wanted to duplicate the default button behavior of HTML forms where when you hit the enter key it would trigger the default button on the form. I did some googling on the subject and came across this post by Patrick Cauldwell which is one way to solve the problem. However, in my case I had a username Textbox, a password Passwordbox, and a company Combobox and didn’t want to specify the button for each control.
So I create a simple solution of creating a content control that attaches to all the KeyUp events of all the child FrameworkElements in the content. To do this I used the FindChildren<T> extension method from the Avanade Silverlight Accelerator which is a toolkit we use internally at Avanade to speed up Silverlight development. The ContentControl exposes a DefaultCommand property which you then bind to the ICommand property on your ViewModel.
Below is a trimmed down example of the Login view. I’m using a variant of the RelayCommand/DelegateCommand as the LoginCommand here (see Laurent’s post on the RelayCommand for a good overview of Commands in Silverlight).
<ctrls:FormControl DefaultCommand="{Binding LoginCommand}"> <TextBox Text="{Binding Username, Mode=TwoWay}" /> <PasswordBox Password="{Binding Password, Mode=TwoWay}" /> <Button IsEnabled="{Binding LoginEnabled}" cmds:ButtonClickCommand.Command="{Binding LoginCommand}" Content="Login" /> </ctrls:FormControl>
There are many other things you could add to this but this is all the functionality that I needed and I decided to keep it simple. Download the class file (plus the extension method) below. Let me know if you find it useful!