Windows Phone: What does InitializeComponent() do?

Coding in XAML is quite ridiculously easy on the face of it, there’s masses of tutorials, samples, guides and step-by-step instructions for building simple applications that solve problems in a pretty elegantly presented UI.

However like a marathon runner, just after you finish those tutorials and start programming in anger, you hit The Wall.  Your controls don’t display properly, binding doesn’t work, events are fired but aren’t received, or worst of all, customers report a problem with the UI that you can’t replicate.

The key to solving problems like this is to really understand what’s going on behind the scenes, under the covers and, most importantly, when you’re not looking.  Ultimately, all the syntactic sugar that is XAML is going to come back to some CLR code drawing pixels on a screen and a series of methods that are being called in a particular order; and when you can actually see them it will often make it blindingly obvious why your masterpiece doesn’t work (and occasionally show you what it was you did wrong and how to do it right).

As every novice learns, when you create a page or control in a Windows Phone application, you get the following

  1. A XAML XML file.
  2. A “code-behind” file that MVVM advises you should never fill in and that you should really consider deleting, putting all your code-behind logic in a ViewModel class.

However, when you build your project you also get a g.cs and a g.i.cs file stored in the obj directory, and as if to taunt your tortured developer soul, they’re identical.  Fortunately, you can ignore g.i.cs files as these appear only to be used by Visual Studio for Intellisense purposes.  g.cs files are generated from the XAML as part of the build of your project.

Inside those files contained the answer to one of the first questions I had when working with WP7:

What does InitializeComponent do and what happens if I put code above it?

This method firstly checks to see it hasn’t been called before, if it has then it returns immediately (so don’t consider calling this twice once you’ve done something horrible to the control hierarchy).  Then, it loads the XAML file, instructing the runtime to create some “stuff” that is then available for use within our object.

Finally it then initialises all those handy properties, one for each control in your XAML file, and initialises them by looking them up in the data interpreted from the XAML.

So, if you put something in your code-behind before InitializeComponent, then expect some NullReferenceExceptions when you attempt to access the internal properties!

The next few posts will be about my adventures with data binding.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.