Add keyboard shortcuts to your MVVM UWP App

by Ishai Hachlili 28. January 2016 07:22


Adding shortcuts to your app will make life easier for your users.

On a PC users would expect shortcuts and now with Windows 10/UWP these shortcuts will work on Mobile apps as well when a keyboard is connected.

When used on a phone with Continuum an app that supports full screen and keyboard shortcuts will give the user a great experience.

I use MVVM for all my apps and I try to avoid code behind in pages (I aim for one line of code in my *.xaml.cs files, InitializeComponent();) so I wanted a nice way to define keyboard interactions in XAML.


Enter Template10

Template10 is an open source project from Jerry Nixon and other Microsoft Developer Evangelists.

There's a lot of good stuff in Template10 but one of the things that caught my eye was the TextBoxEnterKeyBehavior. I quickly used it to add Enter key support in login and search forms.

It's very simple to use:

<TextBox Header="Search:" Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
                              <core:InvokeCommandAction Command="{Binding SearchCommand}"/>

I'm using the InvokeCommandAction to execute a command in my ViewModel but you could use other actions as well (to change focus for example).

Notice the added UpdateSourceTrigger=PropertyChange in the TextBox binding, without it the typed value won't be updated before the command executes (thanks janabimustafa).


Keyboard Shortcuts

Once I saw how simple it is to add keyboard support with a behavior, I decided to add a bunch of shortcuts. Since I now wanted to use other keys and not just the enter key I created a new behavior and added a Key property to it. I also changed the behavior target to Control so you can set it up on a whole page or grid.

 Here's a gist of the new behavior

 To use it add a behavior and define the Key you want to list to:

        <behaviors:KeyUpBehavior Key="Left">
            <core:InvokeCommandAction Command="{Binding ShowPreviousItemCommand}"/>
        <behaviors:KeyUpBehavior Key="Right">
            <core:InvokeCommandAction Command="{Binding ShowNextItemCommand}"/>

Key Modifiers (Control, Shift)

I was using that last sample to control paging, it's much nicer to be able to use the keyboard to move between items but what about saving an item or adding a new one? 

I needed to add support for Control and Shift modifiers. I added another property for the modifier and updated the code to check if modifiers were set.

Here's the diff

To use it in your XAML:

        <behaviors:KeyUpBehavior Key="S" KeyModifier="Control,Shift">
            <core:InvokeCommandAction Command="{Binding SaveAndPublishCommand}"/>
        <behaviors:KeyUpBehavior Key="S" KeyModifier="Control">
            <core:InvokeCommandAction Command="{Binding SaveDraftCommand}"/>

As you can see, you can use one or more modifiers. In this sample I'm using CTRL+S to save a draft and CTRL+SHIFT+S to save and publish.

Now just add tooltips so users can discover your app supports shortcuts (add ToolTipService.ToolTip="Ctrl+S" to the save button for example) and you're all set.

You can actually use this KeyUpBehavior for the Enter key functionality as well.


I hope you find it useful in your apps. 

Tags: , , , ,


Using the MvvmCross PictureChooser plug-in with a Windows Phone 8.1 XAML app

by Ishai Hachlili 30. January 2015 21:23

As we're getting closer to the release of Windows 10 for both phones and PCs I figured it's time to migrate some of my apps from WP Silverlight to WP XAML.

Most of my apps use MvvmCross, which allows me to use MVVM (and binding) with Xamarin.iOS and Xamarin.Android as well as Windows Phone of course.


One of the plugins I often use in my apps is the PictureChooser plugin. This plugin makes it easy to take a picture or choose a picture from the gallery on all platforms with a couple of lines of code in your ViewModel.

Here's a sample ViewModel Code:

        private readonly IMvxPictureChooserTask _pictureChooserTask;

        private const int MaxPicturePixelDimension = 640;
        private const int PictureQuality = 100;

        public FirstViewModel(IMvxPictureChooserTask pictureChooserTask)
            _pictureChooserTask = pictureChooserTask;

        private byte[] _pictureBytes;
        public byte[] PictureBytes
            get { return _pictureBytes; }
            set { _pictureBytes = value; RaisePropertyChanged(()=>PictureBytes); }

        public ICommand SelectPictureCommand
            get { return new MvxCommand(SelectPicture); }

        private async void SelectPicture()
            var pictureStream = await _pictureChooserTask.ChoosePictureFromLibraryAsync(MaxPicturePixelDimension, PictureQuality);

            var memoryStream = new MemoryStream();
            await pictureStream.CopyToAsync(memoryStream);
            PictureBytes = memoryStream.ToArray();

The actual code to launch the picture gallery is that one line of code calling ChoosePictureFromLibrary on the PictureChooserTask. The rest of the code deals with displaying the selected picture.

The plugin also includes the TakePictureAsync method, but in Windows Phone 8.1 there is no separate TakePictureTask, instead, the gallery includes a camera button.

The PictureChooserTask worked great in Windows Phone 8, Android and iOS. With a Windows Phone 8.1 XAML app nothing was happening after I selected a picture.

As I started looking into the MvvmCross code to figure it out, I saw this comments:

            // This method requires that PickFileContinuation is implemented within the Windows Phone project and that
            // the ContinueFileOpenPicker method on the View invokes (via the ViewModel) the ContinueFileOpenPicker method
            // on this instance of the MvxPictureChooserTask

So here's what you need to actually do

  1. Add the ContinuationManager class from Microsoft's documentation to your Windows Phone app
  2. In App.xaml.cs add a ContinuationManager property
    public ContinuationManager ContinuationManager { get; private set; }
  3. Also in App.xaml.cs, override OnActivated and add the following two lines:
      ContinuationManager = new ContinuationManager();
      ContinuationManager.Continue(args as IContinuationActivatedEventArgs);
  4. In your ViewModel class add a public method
      public void ContinueFileOpenPicker(object args)
  5. In the code behind for the view, add the interface IFileOpenPickerContinuable and implement the ContinueFileOpenPicker method:

This code should complete the loop. The PictureChooser plugin's ContinueFileOpenPicker will process the image just like it does for other platforms (in my sample ViewModel above, execution will continue with the stream in the SelectPicture method, as expected)


 Here's the complete project on GitHub

Tags: ,


A Quick Tip for UI design in Windows Phone 8

by Ishai Hachlili 30. October 2012 07:45

If you’ve worked on WP7 apps, you probably came across the MetroGridHelper from Jeff Wilcox. If not, what this little helper does is add a grid of squares that helps you align controls in your app’s pages.

If you’re one of those who ignore the commented sections in newly created pages, you might miss that this feature is now included in the default WP8 project. To use it, all you have to do is uncomment the Image tag at the end of the page

<!--Uncomment to see an alignment grid to help ensure your controls are
aligned on common boundaries. The image has a top margin of -32px to
account for the System Tray. Set this to 0 (or remove the margin altogether)
if the System Tray is hidden.

Before shipping remove this XAML and the image itself.-->
<!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />-->

Tags: , ,

Design | Windows Phone 8

About Ishai

Ishai is the founder of Smart Trivia, Inc. where he builds trivia games for smartphones using MvvmCross and Xamarin. He's also running the Silicon Valley Mobile/Cross Platform .Net Meetup and helps other companies build mobile apps using Xamarin as a consultant

Recent Tweets

Twitter October 23, 05:22
@BenThePCGuy a standard where that doesn't matter is better. One more reason to get the #Lumia920, wireless charging, no need for microUSB

Twitter October 23, 05:21
@ManMadeMoon where they dance around the issues and don't really talk about them

Twitter October 23, 05:20
@BenThePCGuy are you a @wpdev ?

Twitter October 23, 04:17
@JonahLupton But if it's black it's usually better

Twitter October 23, 02:58
@jongalloway next time ask your 5 year old how to spell