Windows Phone 7 - High Performance Code Behind Default Layout

08 September 2010

Not sure why it’s not the default, but this is the recommended way to have a good performant Windows Phone 7 page. Notice how the LayoutUpdated event is used once to ensure the first frame is drawn before we do any heavy lifting.

see Windows Phone Performance Whitepaper here for more

Note that this isn’t strictly required of course, but if you are going to iso storage or calling a web service and such like you really don’t want to be doing that in Loaded event or in OnNavigatedTo, as the page might well not show for a while.

public partial class MainPage : PhoneApplicationPage
{
    private bool _onNavigatedToCalled = false;

    public MainPage()
    {
        InitializeComponent();
        LayoutUpdated += new EventHandler(View_LayoutUpdated);
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        _onNavigatedToCalled = true;
    }

    void View_LayoutUpdated(object sender, EventArgs e)
    {
        if (_onNavigatedToCalled)
        {
            _onNavigatedToCalled = false;
            Dispatcher.BeginInvoke(() =>
            {
                // spin off the heavy lifting here
            });
        }
    }

}
Want to get started?

We would love to help with your next app or game, please do get in touch.