How to save ListView and ScrollViewer family controls scroll position

One of the suggested guidelines when creating a Windows Phone application is that when the user quits an application, the states of the pages are saved, so that when the user re-opens the application, it feels like he never quit.

With the Mango update, it is now possible to save the states of application pages, providing there is enough memory. However, there will be some cases when the application will tombstone. The purpose of my utility static class StateManager will help to save a ListView/ScrollViewer scroll position or other controls that have an internal ScrollViewer.

Before explaining my utility class works, let’s see what happen when the scroll position is not saved:

1- Create a “Windows Phone Databound Application”.
2- Run the app then scroll the list to the last item.
3- Press the Start button.
4- Press the Back button.

The state is preserved. Great, but…

Now, stop debugging the application and go to the properties of the project. In the Debug section, check the option “Tombstone upon deactivation while debugging”. This is the only way to force the tombstoning process while debugging.

Tombstone

Execute the last 3 steps and you’ll see that the list scroll position is not saved.

To fix this issue, insert the StateManager class (provided at the end of the article) in your project and call StateManager.SaveScrollViewerOffset and StateManager.RestoreScrollViewer on the list that you want to save/restore scroll position. The best places to insert those calls are in the method OnNavigatedTo and OnNavigatedFrom.

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    StateManager.RestoreScrollViewerOffset(MainListBox);
    
}

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);

    StateManager.SaveScrollViewerOffset(MainListBox);
}

Download StateManager.cs
Download Sample project

How to fix the standard header of a pivot control using a style and how to fix a page using the TitleControl

When I first read the excellent book 101 Windows Phone 7 Apps by Adam Nathan, I was surprised to learn that if you create a “Windows Phone Application” or a “Windows Phone Pivot Application” in Visual Studio, the application title is not displayed as it is the built-in metro applications of the Windows Phone OS.

If you want to see the differences for yourself, follow these steps:

1- Create a “Windows Phone Pivot Application”.
2- In the MainPage.xaml, change the “MY APPLICATION” title to “SETTINGS”.
3- Change the header name of the first pivot item from “first” to “system”.
4- Change the header name of the second pivot item from “second” to “application”.
5- Run the application.

You’ll see:

BadSettingsPage

Now, exit the application and go in the “Settings” application of the emulator, then look at the page:

GoodSettingsPage

Do you see a difference in the “SETTINGS” application title?

image

To approximate the same design as the OS, the author suggests a style that you can apply to your pivot control:

<Style x:Key="PivotStyle" TargetType="controls:Pivot"> <Setter Property="TitleTemplate"> <Setter.Value> <DataTemplate> <TextBlock FontFamily="{StaticResource PhoneFontFamilySemiBold}" FontSize="{StaticResource PhoneFontSizeMedium}" Margin="-1,-1,0,-3" Text="{Binding}" /> </DataTemplate> </Setter.Value> </Setter> </Style> 

Apply the style:

    <controls:Pivot Title="SETTINGS" Style="{StaticResource PivotStyle}"> 

The same issue happens with every page (PhoneApplicationPage). Instead of applying the fix to all the pages of an application, I created the TitleControl (the code is available for download at the end of the article).

Two of the goals behind the TitleControl were:

1- Get rid of all the XAML code that displays the header.

2- Remove the unnecessary extra grid that displays the header and the content. Remember, if you can have less containers like panels, a grids, or stack panels in a page, your loading speed will be faster.

So, instead of having the following XAML code:

<Grid x:Name="LayoutRoot" Background="Transparent">

 <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock Text="Hello World" /> </Grid>

 </Grid> 

The code can be reduced to:

<Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Controls:TitleControl TitleName="SETTINGS" PageName="theme" /> <TextBlock Grid.Row="1" Margin="24,0" Text="Hello World" /> </Grid> 

If you have a brand theme, you can override the color and the font directly in the TitleControl or you can add additional dependency properties to the control.

Download TitleControl
Download Sample project

How to mimic the application bar of the game hub and to avoid the splash screen bug

With the release of the Mango update, having a minimized application bar with an application using the panorama control is now part of the Metro experience. The best example is the games hub. The minimized application bar uses the Opacity property as you can see in the following picture.

Opacity

To mimic the application bar of the game hub, follow these 2 steps:

1- Add the following XAML code where the panorama control resides to add the application bar.

  <phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar BackgroundColor="DarkGray" ForegroundColor="Black" IsVisible="False" IsMenuEnabled="True" Mode="Minimized" Opacity="0.60" StateChanged="ApplicationBarStateChanged"> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem Text="MenuItem 1" /> <shell:ApplicationBarMenuItem Text="MenuItem 2" /> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar> 

You’ll have this result:

ApplicationBarOpacity

2- In the page with the application bar, add the event handler ApplicationBarStateChanged.

private void ApplicationBarStateChanged(object sender, ApplicationBarStateChangedEventArgs applicationBarStateChangedEventArgs)
{
    ApplicationBar applicationBar = sender as ApplicationBar;

    if (applicationBar != null)
    {
        applicationBar.Opacity = applicationBarStateChangedEventArgs.IsMenuVisible ? 1 : 0.60;
    }
}

The application bar will use a solid color (i.e. no opacity) when it will be expanded. It’s easier to read like this:

ApplicationBarNoOpacity

When I implemented this behaviour in one of my applications, I discovered that the application bar was appearing while the splash screen was shown. It’s very subtle, but it feels like a bug. I saw this bug on some other applications in the Marketplace. Here is a screenshot with the splash screen with the application bar.

SplashScreenBug

To correct this bug, it’s very easy:

1- Make the application bar hidden by default in the XAML code. It’s already included in the first step at the top (IsVisible=”False”).

2- In the page of the application bar, add the event handler Loaded of the page, then add ApplicationBar.IsVisible = true.

private void MainPageLoaded(object sender, RoutedEventArgs e)
{
    if (!App.ViewModel.IsDataLoaded)
    {
        App.ViewModel.LoadData();
    }

    ApplicationBar.IsVisible = true;
}

If you are using the BindableApplicationBar of the Phone7.FX project, I highly suggest reading the perfect solution of Mark Monster that uses a Behavior.

Download Sample project

How to get the Internet connection type without blocking the UI

All Windows Phone applications that use Internet data should always check if there is a valid Internet connection. If there is no connection, a proper message should be displayed to the user. If your application relies on a specific server, don’t assume that Internet is not available if a call to the server returns an error, because the server might be down while the Internet is still available.

The proper way to check if you have an Internet connection (WIFI, Ethernet, or none) is calling the property:

NetworkInterface.NetworkInterfaceType

Unfortunately, even if it’s not obvious, calling this property on the UI thread can block the UI for many seconds. To avoid this problem, I created a NetworkInformationUtility class (the class and the sample project are available at the end of the post):

using System.Threading;
using Microsoft.Phone.Net.NetworkInformation;

namespace DotNetApp.Utilities
{
    public class NetworkTypeEventArgs {
        #region Constructor

        public NetworkTypeEventArgs(NetworkInterfaceType type, bool hasTimeout = false)
        {
            Type = type;
            HasTimeout = hasTimeout;
        }

        #endregion #region Properties

        public bool HasTimeout { get; private set; }

        public bool HasInternet
        {
            get { return Type != NetworkInterfaceType.None; }
        }

        public NetworkInterfaceType Type { get; private set; }

        #endregion }

    /// <summary> /// Static class to get the NetworkInterfaceType without blocking the UI thread. /// </summary> public static class NetworkInformationUtility {
        #region Fields

        private static bool _isGettingNetworkType;
        private static readonly object _synchronizationObject = new object();
        private static Timer _timer;

        #endregion #region Methods

        /// <summary> /// Get the NetworkInterfaceType asynchronously. /// </summary> /// <param name="timeoutInMs">Specifies the timeout in milliseconds.</param> public static void GetNetworkTypeAsync(int timeoutInMs)
        {
            lock (_synchronizationObject)
            {
                if (!_isGettingNetworkType)
                {
                    _isGettingNetworkType = true;

                    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                    {
                        Thread thread = new Thread(GetNetworkType) {IsBackground = true};
                        thread.Start(timeoutInMs);
                    }
                    else {
                        FireGetNetworkTypeCompleted(NetworkInterfaceType.None);
                    }
                }
            }
        }

        #endregion #region Delegates

        public delegate void NetworkTypeEventHandler(object sender, NetworkTypeEventArgs networkTypeEventArgs);

        #endregion #region Events

        public static event NetworkTypeEventHandler GetNetworkTypeCompleted;

        #endregion #region Event Handlers

        private static void OnTimerElapsed(object state)
        {
            FireGetNetworkTypeCompleted(NetworkInterfaceType.None, true);
        }

        #endregion #region Private Methods

        private static void GetNetworkType(object state)
        {
            _timer = new Timer(OnTimerElapsed, null, (int)state, 0);

            // This is a blocking call, this is why a thread is used to let the UI to be fluid NetworkInterfaceType type = NetworkInterface.NetworkInterfaceType;

            _timer.Dispose();
            _timer = null;

            FireGetNetworkTypeCompleted(type);
        }

        private static void FireGetNetworkTypeCompleted(NetworkInterfaceType type, bool hasTimeout = false)
        {
            lock (_synchronizationObject)
            {
                if (_isGettingNetworkType)
                {
                    _isGettingNetworkType = false;

                    NetworkTypeEventHandler networkTypeEventHandler = GetNetworkTypeCompleted;

                    if (networkTypeEventHandler != null)
                    {
                        networkTypeEventHandler(null, new NetworkTypeEventArgs(type, hasTimeout));
                    }
                }
            }
        }

        #endregion }
}

Here are the steps to use this class in your code:

  1. Add the NetworkInformationUtility.cs to your project.
  2. Attach method to the event NetworkInformationUtility.GetNetworkTypeCompleted.
  3. Call NetworkInformationUtility.GetNetworkTypeAsync(3000 /*timeout in ms*/);
  4. Retrieve the result on the GetNetworkTypeCompleted method that you attached to the event.

Code sample:

using System.Windows;
using DotNetApp.Utilities;

namespace NetworkInformationApp
{
    public partial class MainPage {
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            NetworkInformationUtility.GetNetworkTypeCompleted += GetNetworkTypeCompleted;

            NetworkInformationUtility.GetNetworkTypeAsync(3000); // Timeout of 3 seconds }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            NetworkInformationUtility.GetNetworkTypeCompleted -= GetNetworkTypeCompleted;
        }

        private void GetNetworkTypeCompleted(object sender, NetworkTypeEventArgs networkTypeEventArgs)
        {
            string message;

            if (networkTypeEventArgs.HasTimeout)
            {
                message = "The timeout occurred";
            }
            else if (networkTypeEventArgs.HasInternet)
            {
                message = "The Internet connection type is: " + networkTypeEventArgs.Type.ToString();
            }
            else {
                message = "There is no Internet connection";
            }

            // Always dispatch on the UI thread Dispatcher.BeginInvoke(() => MessageBox.Show(message));
        }
    }
}

Download NetworkInformationUtility.cs
Download Sample project

Canadian Developer Connection and AlignIT applications

For the great Developer Movement promotion, I had an idea to create an application from the content of the Canadian Developer Connection blog by our beloved Microsoft evangelists of Canada. The content of the blog is helpful for all developers around the world using Microsoft technologies. With their permission, I created the Canadian Developer Connection application:

The 3 main features of the app are:

  • Read articles and watch saved videos while you are on the go (i.e. without an Internet connection).
  • Receive notifications for unread posts and news on Live Tile.
  • Pin your favourite evangelists in the Start menu for quick access.

For those who don’t know about the Developer Movement promotion, if you build quality apps, you can get a Kinect, a 1 TB external hard drive, a Windows Phone, a 500$ gift voucher and so on.

For an additional app for the Developer Movement promotion, I created the AlignIT application. This application is based from the content of the AlignIT website. AlignIT is the one-stop source for Canadian infrastructure and development managers. The application is built with the same framework as the Canadian Developer Connection application, so contains the same feature set.

Welcome to my new blog!

Hello,

It is with a warm welcome that I invite you to read my new blog.

The blog will be dedicated to Windows Phone development, but from time to time you may also see some Windows 8 articles. Windows Phone and Windows 8 share the amazing Metro style, and a lot of the code is the same.

In the two years since I started developing for the Windows Phone platform, many extraordinarily cool things have happened to me. If you keep reading my blog, you will discover what these cool events have been, and you will also learn some tricks that will help you be successful in developing your own Windows Phone apps.

As a side note, please be aware that my first language is French, and so any grammatical errors are unintentional. I will try to do my best. Errors in code, however, you can blame me for!

Through the platform of my blog, I would like to share my passion for Windows Phone development, and I hope I’ll be able to help the WP community create more wonderful applications.

Happy coding!

Sébastien, alias ArchieCoder