Saturday, September 18, 2010

Windows Phone 7 Quick Tip #5 – Dismissing Popups Controls

Generally it’s not a good idea to use Popups in your Windows Phone 7 application, however just as any rule of thumb, there are exceptions.

Here’s some XAML to add the Popup to your control or page:

<Grid x:Name="LayoutRoot"  >
       <Popup x:Name="MyPopup" Width="400" Margin="20"
                  VerticalAlignment="Top" >
                   <YOUR XAML HERE>

       </Popup>
</Grid>

To show the popup:

MyPopup.IsOpen = true;

Closing the Popup is as easy as setting the IsOpen property to false.

To provide a more seamless experience to your users you may want to wire in to the hardware back button to dismiss the popup control.  You need to do this manually however it’s relatively easy to do.  What we do is override the OnBackKeyPress method in your page and set the Cancel property to true on the CancelEventArgs instance passed to your override.

protected override void OnBackKeyPress(CancelEventArgs e)
{
    if (MyPopup.IsOpen)
    {
        MyPopup.IsOpen = false;
        e.Cancel = true;
    }

    base.OnBackKeyPress(e);
}

And it’s just that simple, now if your popup is visible and the user presses the back key on the Windows Phone 7 device, instead of navigating to the previous screen, the popup will be dismissed.

1 comment: