Extending the platform with ICommands

The ICommand interface has been around for a long time now. It is typically used in a desktop application, for example, to allow the simple binding of buttons or menu items to an action in the code behind, and can be extremely useful.

A common scenario in Windows 8 where command support would be useful is on the click event of a GridView item – for example, an item on your main menu screen. Unfortunately, the platform doesn’t support commands here out of the box, so we have to do some juggling and introduce an attached property to do the work for us.

Let’s start by creating a class to hold the attachable property.

Once we have that set up, we need to define an ICommand in our view model. In this case, I’m using MvvmLight, so I’ll use the RelayCommand type.

Next, we need to wire up the ItemClick event on the GridView (or ListView – both will work with this property)

The last step is to wire up the main page to listen for navigation messages from the ViewModel’s command.

Now, when you run your app, you should be able to navigate to the clicked item (or if you haven’t changed the code, see a MessageDialog with the item id). Note that in the command’s CanExecute method, I only allow navigation to items whose Id is an even number.

GridTapCommand Example (.zip 28kb)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">