Daniel Vaughan

free range code

Loading Data when the User Scrolls to the End of a List in Windows Phone 7

clock January 24, 2011 22:18 by author Daniel Vaughan

Most phone users are concerned about network usage. Network traffic comes at a premium, and a user's perception of the quality of your app depends a lot on its responsiveness. When it comes to fetching data from a network service, it should be done in the most efficient manner possible. Making the user wait while your app downloads giant reams of data doesn't cut it. It should, instead, be done in bite-sized chunks.

To make this easy for you, I have created a ScrollViewerMonitor which uses an attached property to monitor a ListBox and fetch data as the user needs it. It's as simple as adding an attached property to a control which contains a ScrollViewer, such as a ListBox, as shown in the following example:

<ListBox ItemsSource="{Binding Items}"
         u:ScrollViewerMonitor.AtEndCommand="{Binding FetchMoreDataCommand}" />

Notice the AtEndCommand. That's an attached property that allows you to specify a command to be executed when the user scrolls to the end of the list. Easy huh! I'll explain in a moment how this is accomplished, but first some background.


For almost the last year, I've been building infrastructure for WP7 development. A lot has been going into the book I am writing, and even more is making its way into the upcoming Calcium for Windows Phone. I am pretty much at bursting point; wanting to get this stuff out there.

The chapter of Windows Phone 7 Unleashed, which discusses this code, demonstrates an Ebay search app that makes use of the Ebay OData feed (see Figure 1). It's simple, yet shows off some really nice techniques for handling asynchronous network calls.

Figure 1: The Ebay Seach app from Windows Phone 7 Unleashed.


The Ebay app isn't in the downloadable code for this post. But there is a simpler app that displays a list of numbers instead.

The way the ScrollViewerMonitor works is by retrieving the first child ScrollViewer control from its target (a ListBox in this case). It then listens to its VerticalOffset property for changes. When a change occurs, and the ScrollableHeight of the scrollViewer is the same as the VerticalOffset, the AtEndCommand is executed.


public class ScrollViewerMonitor
    public static DependencyProperty AtEndCommandProperty
        = DependencyProperty.RegisterAttached(
            new PropertyMetadata(OnAtEndCommandChanged));

    public static ICommand GetAtEndCommand(DependencyObject obj)
        return (ICommand)obj.GetValue(AtEndCommandProperty);

    public static void SetAtEndCommand(DependencyObject obj, ICommand value)
        obj.SetValue(AtEndCommandProperty, value);

    public static void OnAtEndCommandChanged(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
        FrameworkElement element = (FrameworkElement)d;
        if (element != null)
            element.Loaded -= element_Loaded;
            element.Loaded += element_Loaded;

    static void element_Loaded(object sender, RoutedEventArgs e)
        FrameworkElement element = (FrameworkElement)sender;
        element.Loaded -= element_Loaded;
        ScrollViewer scrollViewer = FindChildOfType<ScrollViewer>(element);
        if (scrollViewer == null)
            throw new InvalidOperationException("ScrollViewer not found.");

        var listener = new DependencyPropertyListener();
            += delegate
                bool atBottom = scrollViewer.VerticalOffset
                                    >= scrollViewer.ScrollableHeight;

                if (atBottom)
                    var atEnd = GetAtEndCommand(element);
                    if (atEnd != null)
        Binding binding = new Binding("VerticalOffset") { Source = scrollViewer };
        listener.Attach(scrollViewer, binding);

    static T FindChildOfType<T>(DependencyObject root) where T : class
        var queue = new Queue<DependencyObject>();

        while (queue.Count > 0)
            DependencyObject current = queue.Dequeue();
            for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
                var child = VisualTreeHelper.GetChild(current, i);
                var typedChild = child as T;
                if (typedChild != null)
                    return typedChild;
        return null;


Of course there is a little hocus pocus that goes on behind the scenes. The VerticalOffset property is a dependency property, and to monitor it for changes I've borrowed some of Pete Blois's code, which allows us to track any dependency property for changes. This class is called BindingListener and is in the downloadable sample code.

Sample Code

The ViewModel for the MainPage contains a FetchMoreDataCommand. When executed, this command sets a Busy flag, and waits a little while, then adds some more items to the ObservableCollection that the ListBox in the view is data-bound too.


public class MainPageViewModel : INotifyPropertyChanged
    public MainPageViewModel()

        fetchMoreDataCommand = new DelegateCommand(
            obj =>
                    if (busy)
                    Busy = true;
                            /* This is just to demonstrate a slow operation. */
                            /* We invoke back to the UI thread. 
                                * Ordinarily this would be done 
                                * by the Calcium infrastructure automatically. */
                                    Busy = false;

    void AddMoreItems()
        int start = items.Count;
        int end = start + 10;
        for (int i = start; i < end; i++)
            items.Add("Item " + i);

    readonly DelegateCommand fetchMoreDataCommand;

    public ICommand FetchMoreDataCommand
            return fetchMoreDataCommand;

    readonly ObservableCollection<string> items = new ObservableCollection<string>();

    public ObservableCollection<string> Items
            return items;

    bool busy;

    public bool Busy
            return busy;
            if (busy == value)
            busy = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Busy"));

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        var tempEvent = PropertyChanged;
        if (tempEvent != null)
            tempEvent(this, e);


There's a lot more infrastructure provided with the book code. But I tried hard to slim everything down for this post. The MainPage.xaml contains a Grid with a ProgressBar, whose visbility depends on the Busy property of the viewmodel.


<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    <ListBox ItemsSource="{Binding Items}"
                u:ScrollViewerMonitor.AtEndCommand="{Binding FetchMoreDataCommand}">
                <StackPanel Orientation="Horizontal">
                    <Image Source="Images/WindowsPhoneExpertsLogo.jpg" 
                            Margin="10" />
                    <TextBlock Text="{Binding}" 
                                Style="{StaticResource PhoneTextTitle2Style}"/>                            
    <Grid Grid.Row="1"
            Visibility="{Binding Busy, 
                Converter={StaticResource BooleanToVisibilityConverter}}">
            <RowDefinition />
            <RowDefinition />
        <TextBlock Text="Loading..." 
                    Style="{StaticResource LoadingStyle}"/>
        <ProgressBar IsIndeterminate="{Binding Busy}"
                        Grid.Row="1" />


You may be wondering why there is a databinding for ProgressBar's IsIndeterminate property. This is for performance reasons, as when indeterminate the ProgressBar is notorious for consuming CPU. Check out Jeff Wilcox's blog for a solution.

Now, when the user scrolls to the bottom of the list, the FetchMoreDataCommand is executed, providing an opportunity to call some network service asynchronously (see Figure 2).



Figure 2: Loading message is displayed when the user scrolls to the end of the list.


I hope you enjoyed this post, and that you find the attached code useful.

If you are interested in up-to-the-minute WP7 info, check out the Windows Phone Experts group on LinkedIn.


DanielVaughan.ScrollViewerMonitor.zip (126.56 kb)


Follow me on twitter

Calcium Downloads Surpass 10,000

clock January 12, 2011 12:30 by author Daniel Vaughan

Interest in the Calcium project has been huge this year. So much so that the number of downloads for Calcium has passed 10,000.

In the works for this year is a Windows Phone version of Calcium, which I have been implicitly working on during the writing of Windows Phone 7 Unleashed. I will also be improving support for the Silverlight for the desktop version of Calcium.

If you're a Calcium user, and have feature requests, be sure to add them to the tracker. I use that a lot to determine the priority of new features.

Refresh a WP7 PhoneApplicationPage

clock January 5, 2011 19:03 by author Daniel Vaughan

Here is a quick a dirty way to refresh a WP7 page. We use the NavigationService to navigate to the current page. There's a catch though (in fact there are two but we'll get to the second in a moment), we need to make a change to the Uri, else the NavigationService thinks we are trying to perform fragment navigation, which is not supported, and will raise an exception. A work-around is to tack a query string on the end, as shown in the following example:


void Button_Click(object sender, RoutedEventArgs e)
NavigationService.Navigate(new Uri(NavigationService.Source + "?Refresh=true"UriKind.Relative));


Keep in mind that this will cause the page to be placed on the history stack, which is not desirable as the hardware back button will cause the page to refresh, again.

Now the trouble with this approach, as Scott Cate points out, is that we end up having multiple query string parameters appended. Here is another approach that uses a counter:


static int refreshCount;

void Button_Click(object sender, RoutedEventArgs e)
string url = NavigationService.Source.ToString();

if (!url.Contains("RefreshCount="))
if (NavigationContext.QueryString.Count < 1)
url += "?RefreshCount=" + ++refreshCount;
url += "&RefreshCount=" + ++refreshCount;
url = Regex.Replace(url, @"RefreshCount=+\d""RefreshCount=" + ++refreshCount);
NavigationService.Navigate(new Uri(url, UriKind.Relative));

I don't particularly recommend refreshing a page. It would be best to replace the datacontext for a page. But if you absolutely must, there you have it.



CodeProject MVP 2011

clock January 4, 2011 11:02 by author Daniel Vaughan

I'm humbled to be re-awarded the status of CodeProject MVP for 2011. Considering that there are millions of Codeproject members, yet only 40 MVPs, it's a huge honour. Congratulations to my fellow awardess including Sacha Barber, Josh Smith, Pete O'Hanlon, and Michael Washington, and all of these great people:


Dalek Dave

Abhijit Jana

Abhishek Sur


Abhinav S


Sandeep Mewara

Marcelo Ricardo de Oliveira




William Winner


Alan Beasley


Christ Kennedy

Al-Farooque Shubho

Henry Minute

Apriorit Inc

Sauro Viti

Arik Poznanski

Omar Al Zabir

Daniel Vaughan

Josh Smith

Pete O'Hanlon

John Simmons / outlaw programmer

Christian Graus

Mark Nischalke


Nishant Sivakumar

Shivprasad koirala

Md. Marufuzzaman


E.F. Nijboer


Ajay Vijayvargiya

Dave Kreskowiak

Sacha Barber

Richard MacCutchan

Luc Pattyn


Custom Application Bar to Feature in Chapter

clock December 20, 2010 21:10 by author Daniel Vaughan

I've created a custom Windows Phone 7 application bar for a chapter entitled Taming the Application Bar. It supports data-binding, ICommands, button and menu item visibility, toggle buttons, and even multiple application bars for Pivots. 

I'll be releasing the source soon, and I'm really looking forward to getting it out there.

Windows Phone 7 Unleashed

Photo Location: a Windows Phone 7 Marketplace Application

clock November 19, 2010 19:50 by author Daniel Vaughan


Katka has just published a new application to the Windows Phone Marketplace. It's called Photo Location, and it allows you to visualise the geographical location of any photo that is stored on your phone. Here's the blurb:

You can browse through your photos on the Pictures Hub, and if you are ever wondering where a particular photo was taken, simply select Photo Location from the extras menu option in the application bar, and Photo Location will pinpoint the geographical location of your photo on the map. If you launch the application from the application list, Photo Location will take you directly to the Pictures Hub, where you can select any photo, and visualise where it was taken on a map. Not all photos will include GPS information, and Photo Location will only be able to show the location of photos that do include this information. The good news is, however, that the camera on your phone can be configured to include the location information whenever you take a photo, and is probably already setup to do so.

If you have the Zune software installed, you can take a look.




Debugging the PhotoChooserTask and other Media Hub Related Tasks on WP7

clock November 14, 2010 15:56 by author Daniel Vaughan

Using the device debugger is a snap in Windows Phone 7. There are many benefits, and you can see your app executing in a real world environment, with most of the launchers and choosers available for testing. Some choosers, however, rely on the Windows Phone Media Hub; such as the PhotoChooserTask. Trying to debug across a call to that bad boy, with the Zune software running, will lock up your app.

Fortunately there's an easy to use tool that solves the problem by removing the need to have the Zune software running while debugging. It's called the Windows Phone Connect Tool. It was released as part of the recent update to the Windows Phone Developer Tools. This tool allows you to close the Zune software, after your phone device is connected; which means that choosers such as the PhotoChooserTask are able to function correctly while you are debugging.

There are a few steps to launching the tool. Opening a command prompt, navigating to a directory, launching the tool. So I've wrapped these steps up into a batch file which takes care of detecting the platform, locating the path to the WPConnect executable, and launching the tool. The steps for using the batch file are as follows:

  1. Connect your Windows Phone to your computer and ensure that it is detected by the Zune software.
  2. Close the Zune software after your Windows Phone is connected.
  3. Double click on the batch file.

Download it here (1 Kb) [Updated 24 Mar 2011)

Alternatively, to use the Windows Phone Connect Tool manually, follow these steps:

  1. Open a command prompt and navigate to the directory containing the Windows Phone Connect Tool (WPConnect.exe). The location of this file will be %ProgramFiles%\Microsoft SDKs\Windows Phone\v7.0\Tools\WPConnect.
  2. Connect your Windows Phone to your computer and ensure that it is detected by the Zune software.
  3. Close the Zune software after your Windows Phone is connected.
  4. At the command prompt, enter the command WPConnect.exe.

Work-Around for DataContractJsonSerializer ArgumentNullExceptions

clock October 25, 2010 00:50 by author Daniel Vaughan

If you've tried using a DataContractJsonSerializer or a DataContractSerializer with Push Notification for the Windows Phone, you may have experienced an ArgumentNullException during deserialization. This can happen because the MemoryStream is buffered with null characters '\0' that prevent deserialization. A solution is to create a new array and copy all bytes except for the trailing nulls, as shown in the following excerpt from the downloadable sample code in my upcoming book Windows Phone 7 Unleashed:

using (BinaryReader reader = new BinaryReader(bodyStream))
byte[] bodyBytes = reader.ReadBytes((int)bodyStream.Length);

int lengthWithoutNulls = bodyBytes.Length;
for (int i = bodyBytes.Length - 1; i >= 0 && bodyBytes[i] == '\0'
i--, lengthWithoutNulls--)
/* Intentionally left blank. */

byte[] cleanedBytes = new byte[lengthWithoutNulls];
Array.Copy(bodyBytes, cleanedBytes, lengthWithoutNulls);

DataContractJsonSerializer serializer
new DataContractJsonSerializer(typeof(StockQuote));

using (MemoryStream stream = new MemoryStream(cleanedBytes))
StockQuote = (StockQuote)serializer.ReadObject(stream);

Have a great day!


Windows Phone Developer Tools October 2010 Update

clock October 22, 2010 23:53 by author Daniel Vaughan

In case you haven't heard, there's an update for the Windows Phone Developer Tools that was released on 21 October (yesterday as I write this).

The Windows Phone Developer Tools October 2010 Update includes:

  • Windows Phone Capability Detection Tool – Detects the phone capabilities used by your application. When you submit your application to Windows Phone Marketplace , Microsoft performs a code analysis to detect the phone capabilities required by your application and then replaces the list of capabilities in the application manifest with the result of this detection process. This tool performs the same detection process and allows you to test your application using the same list of phone capabilities generated during the certification process. For more information, see How to: Use the Capability Detection Tool.
  • Windows Phone Connect Tool – Allows you to connect your phone to a PC when Zune® software is not running and debug applications that use media APIs. For more information, see How to: Use the Connect Tool.
  • Updated Bing Maps Silverlight Control – Includes improvements to gesture performance when using Bing™ Maps Silverlight® Control.


Download Page

Netflix WP7 Browser

clock October 15, 2010 21:19 by author Daniel Vaughan



Katka has published a great new article http://www.codeproject.com/KB/windows-phone-7/NetflixBrowser.aspx

Learn how to use the Pivot and Panorama controls, page navigation, OData and more!

Order the Book

Ready to take your Windows Phone development skills to the next level? My book is the first comprehensive, start-to-finish developer's guide to Microsoft's Windows Phone 8. In it I teach through complete sample apps that illuminate each key concept with fully explained code and real-world context. Windows Phone 8 Unleashed

Windows Phone Experts Windows Phone Experts
LinkedIn Group



Daniel VaughanDaniel Vaughan is co-founder and president of Outcoder, a Swiss software and consulting company dedicated to creating best-of-breed user experiences and leading-edge back-end solutions, using the Microsoft stack of technologiesin particular WPF, WinRT, and Windows Phone. 

Daniel is a four-time Microsoft MVP for Client Application Development, with experience across a wide range of industries including finance, e-commerce, and digital media. 
Daniel is the author of Windows Phone 7.5 Unleashed and Windows Phone 8 Unleashed, published by SAMS.

Daniel is a Silverlight and WPF Insider, a member of the WPF Disciples, and a member of the Microsoft Developer Guidance Advisory Council.
Daniel also sits on the advisory board of PebbleAge, a Swiss Financial Software company.

While originally from Australia and the UK, Daniel is currently based in Zurich Switzerland. 

Daniel is the developer behind several acclaimed Windows Phone apps including Intellicam and Splashbox; and is the creator of a number of popular open-source projects including the Calcium and Clog.

Daniel also manages the Windows Phone Experts group on LinkedIn; a group that has over 3000 independent developers, Microsoft employees, and Windows Phone enthusiasts.

E-mail Send mail


Microsoft MVP logo Disciple
WPF and Silverlight Insiders



Sign in