Feed Icon  

Contact

  • Bryant Likes
  • Send mail to the author(s) E-mail
  • twitter
  • View Bryant Likes's profile on LinkedIn
  • del.icio.us
Get Microsoft Silverlight
by clicking "Install Microsoft Silverlight" you accept the
Silverlight license agreement

Hosting By

Hot Topics

Tags

Open Source Projects

Archives

Ads

A “Default Command” for Silverlight

Posted in Avanade | Silverlight at Monday, September 28, 2009 7:23 AM Pacific Daylight Time

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!

Tuesday, November 17, 2009 12:36:50 AM (Pacific Standard Time, UTC-08:00)
Hey, thanks that is a nice solution, your doing a goo job with silverlight.
REgards
Galilea
Thursday, November 26, 2009 11:23:29 PM (Pacific Standard Time, UTC-08:00)
This blog contains really good stuff.Thanks for sharing this information.
Comments are closed.