Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

‘Object reference not set to an instance of an object’ Error in WinRT Data Binding

 Data_Model

My current project was plagued with the above error on every XAML page and control, and my design-time data binding had stopped working entirely. My DesignTimeData class seemed correct (at first glance), but the error was saying something in my DesignTimeData class was not correctly instantiated.

I was baffled. Then I realised…

Although the objects in my DesignTimeData class were being instantiated correctly in the constructor, some of those objects relied on other data that was only available at runtime, and the error was filtering down from other classes. For example:


class DesignTimeData

{

    public Starship Enterprise {get; set;}

    public DesignTimeData()

    {

        Enterprise = new Starship();

    }

}

Imagine the Starship class’s constructor accesses some data or class that exists at runtime but not at design time. This will cause the ‘Object reference not set to an instance of an object’ error to filter down to the DesignTimeData class at design time, and design-time data binding will fall over.

Here’s how I solved my problem:

  1. To verify that it is the problem described above, comment out the DesignTimeData constructor, then rebuild. If the error goes away you have the above issue.
  2. Assuming you eliminated the error, go through your constructor and narrow down the culprit. Check the constructors of all objects and make sure they are only referencing things that are available at design time (e.g. not trying to access data downloaded from the Internet at runtime). If you are struggling, simply comment out all lines in the DesignTimeData constructor and uncomment them one-by-one then rebuild until you narror down the error source.

Once you find the culprit you can work around it (or if it’s a bug fix it).

Tags:

Leave a Reply

Your email address will not be published.