How to avoid a "object reference not set to an instance of an object" exception in XAML code at design time? How to avoid a "object reference not set to an instance of an object" exception in XAML code at design time? wpf wpf

How to avoid a "object reference not set to an instance of an object" exception in XAML code at design time?


If you have 'Object reference not set to an instance of an object' in XAML, but your application compiles and runs fine, you will usually find out that its cause is something in a constructor that can't be resolved at design time.

You can just click the "Disable project code" button located on the bottom of your designer view and Visual Studio designer will stop trying to construct an instance to provide design time data view.

See here for detailed information and screenshots.


Whatever is happening in your constructor is throwing an exception during design time. I had same problem - I just put a try catch around the problematic code - in my case I was calling ServiceLocator.Current as I am using an IoC container. But there is no container during design time. So I wrapped in a try catch to suppress the error and it worked. Not the best solution... but its a solution.


I tend to use the LicenseManager class in System.ComponentModel to avoid my ViewModels throwing nasty errors at designtime. For example:

public MyViewModel(){  if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)  {    // Do runtime stuff  }}