Home > C#, WinRT > Remember to unsnap before calling a WinRT Picker

Remember to unsnap before calling a WinRT Picker

25/01/2013

If you try to call a WinRT Picker when you app is snapped, you’ll get a COMException: a Picker can’t be shown in a such situation. To solve this issue, you must ensure that your app is unsnapped. A method from MSDN documentation comes to help:

private bool EnsureUnsnapped()
{
    // using Windows.UI.ViewManagement;
    bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || 
                                                ApplicationView.TryUnsnap());
    return unsnapped;
}

The EnsureUnsnapped method checks whether the app isn’t in snapped mode or, if so, tries to unsnap it. It then returns a value indicating if the app is currently unsnapped.

Using this approach, you can safely call the Picker. For example, with a ContactPicker you can have something like this:

private async void btnGetContact_Click(object sender, RoutedEventArgs e)
{            
    if (EnsureUnsnapped())
    {
        var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
        var contact = await picker.PickSingleContactAsync();
        if (contact != null)
            txbContact.Text = string.Format("Contact name name: {0}", contact.Name);
        else
            txbContact.Text = "Selection cancelled";
    }
}
Categories: C#, WinRT
%d bloggers like this: