21

I have a problem with a wpf usercontrol which is of my own devising. The problem is that I get a object reference not set to an instance of an object exception in XAML code at design time, when I implement the usercontrol in my program.

The designer showed me the following information:

at
Microsoft.Expression.Platform.InstanceBuilders.InstanceBuilderOperations.InstantiateType(Type
type, Boolean supportInternal)    at
Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.InstantiateTargetType(IInstanceBuilderContext
context, ViewNode viewNode)    at
Microsoft.Expression.Platform.InstanceBuilders.ClrObjectInstanceBuilder.Instantiate(IInstanceBuilderContext
context, ViewNode viewNode)    at
Microsoft.Expression.WpfPlatform.InstanceBuilders.FrameworkElementInstanceBuilder.Instantiate(IInstanceBuilderContext
context, ViewNode viewNode)    at
Microsoft.Expression.WpfPlatform.InstanceBuilders.UserControlInstanceBuilder.Instantiate(IInstanceBuilderContext
context, ViewNode viewNode)    at
Microsoft.Expression.Platform.InstanceBuilders.ViewNodeManager.CreateInstance(IInstanceBuilder
builder, ViewNode viewNode)

but I think these messages are not really helpful...

How can I fix or suppress this exception?

Jasperan
  • 2,154
  • 1
  • 16
  • 40
Kimbo
  • 1,328
  • 3
  • 9
  • 12
  • 1
    The designer should show you the stack trace of the error - where is the error actually occurring? – Tim Jul 17 '13 at 13:48
  • Please post the part of the code that throws the error. Its really hard to answer the question with the information provided – Koushik Jul 17 '13 at 14:05
  • 1
    possible duplicate of [WPF, 'Object reference not set to an instance of an object' in Designer](http://stackoverflow.com/questions/3533539/wpf-object-reference-not-set-to-an-instance-of-an-object-in-designer) – Viv Jul 17 '13 at 14:06
  • 1
    yes i know the other question but not any of the descriped solutions solve my problem. I read the other question before i ask this one. – Kimbo Jul 18 '13 at 05:29

14 Answers14

31

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.

Lirrik
  • 795
  • 11
  • 17
  • 3
    If the designer on the current xaml does not load, the "Disable project code" button will not be available. Load a good xaml to make the button available. The setting will now be applied to the xaml which refuses to load. – Alan Wayne Apr 20 '18 at 09:02
  • 1
    if you don't see buttons, try to comment the propblamitc lines and then you will get it – Majid khalili Jul 26 '19 at 20:13
  • I had some code in my constructor that caused this manifestation to occur - it was bugging me (so to speak) glad you helped me out here. – Vidar May 05 '20 at 14:44
  • In my VS that button gives me the option to "display all controls", or "only display platform controls". Choosing the latter causes the xaml to render in the designer and removes the object reference not set to an instance of an object error. – windowsill Nov 27 '21 at 18:50
8

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.

Shumii
  • 4,529
  • 5
  • 32
  • 41
  • This answer makes 0 sense. The issue is in a XAML and there is no way to "just put a try catch" around that. If a person knew what the "problematic code" was there wouldn't be a problem. – N_tro_P Jun 11 '19 at 15:25
  • @N_tro_P There is a .cs file behind the xaml which has a constructor. – Shumii Jun 11 '19 at 19:12
  • Do you think that wrapping a try catch around InitializeComponent() is going to catch the problematic code? Also... Some XAML does NOT have a constructor, such as a resource dictionary. This in particular is my case and how I ended up here. – N_tro_P Jun 12 '19 at 12:56
  • I do not think .Net design time errors care about your beliefs. Again, there isn't even necessarly a code behind. Perhaps in the posters case as in the details he states "user control", but the question is about how to handle a design time error in XAML which could also be a RD. There is no constructor in such a case. – N_tro_P Jun 12 '19 at 13:00
  • 1
    Well may be it does not apply in your case. I think if you share your specifics and how you solved it, that would be more productive than rhetoric. – Shumii Jun 12 '19 at 13:01
  • I haven't solved it... If I did, I would post that answer. – N_tro_P Jun 12 '19 at 13:02
5

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
  }
}
Gareth
  • 2,746
  • 4
  • 30
  • 44
3

Tweaking @BobHorn's example, I got this to work for me:

public class ViewModel
{
    public ViewModel()
    {
        if (!IsInDesignMode)
        {
            //Constructor code here...
        }
    }
    public bool IsInDesignMode
    {
        get
        {
            var prop = DesignerProperties.IsInDesignModeProperty;
            return (bool)DependencyPropertyDescriptor
                .FromProperty(prop, typeof(FrameworkElement))
                .Metadata.DefaultValue;
        }
    }
}

Though using his exact suggestion for the constructor

public Main()
{
    if (IsInDesignMode) { return; }
    //Constructor code here...
}

Did also work for me, I just prefer not short-circuiting my methods with extra return statements. I would have up-voted his answer, don't have the rep yet.

aherocalledFrog
  • 831
  • 9
  • 13
3

When you work on a WIndow/UserControl in the designer it "runs" the parameterless constructor. If you have code in there which is reliant on something usually provided by some other piece of code then this often causes a problem. The designer doesn't run any other code first so dependencies usually provided elsewhere can be missing and cause errors. Suppressing these is a matter of detecting whether that code is running in the designer or not. It's often most convenient to just return out the constructor:

public MainWindow()
{
    InitializeComponent();
    if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
        return;

    //code
}

More in detail https://social.technet.microsoft.com/wiki/contents/articles/29874.aspx?Redirected=true

Raj
  • 31
  • 1
2

You could do something like this:

using System.ComponentModel;
using System.Windows;

/// <summary>
/// WPF Design Mode helper class.
/// </summary>
public static class DesignMode
{
    private static bool? _isInDesignMode;

    /// <summary>
    /// Gets a value indicating whether the control is in design mode (running in Blend
    /// or Visual Studio).
    /// </summary>
    public static bool IsInDesignMode
    {
        get
        {
            if (!_isInDesignMode.HasValue)
            {
                var prop = DesignerProperties.IsInDesignModeProperty;
                _isInDesignMode
                    = (bool)DependencyPropertyDescriptor
                    .FromProperty(prop, typeof(FrameworkElement))
                    .Metadata.DefaultValue;
            }

            return _isInDesignMode.Value;
        }
    }
}

Then, as the first line in the constructor of your view (or view model), you can do something like this:

if (DesignMode.IsInDesignMode) { return; }

That way your code will only run when you're actually running it.

Bob Horn
  • 33,387
  • 34
  • 113
  • 219
2

I had the similar problem. You just need to go to Tools> Options> XAML Designer and enable the option

"Run project code in XAML designer".

Finally restart Visual Studio. I hope this will help.

Dark Knight
  • 819
  • 8
  • 12
1

Had this issue for VS2022 17.5.4 for certain components (like TabControl) in XAML (this issue only happened after recent vs updates)

Found this solution from google:

xaml preview Only Display Platform Controls

Then noticed that @windowsill comment has mentioned this also How to avoid a "object reference not set to an instance of an object" exception in XAML code at design time?

mgear
  • 1,333
  • 2
  • 22
  • 39
0

VS 2017 UWP:

if (false == Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
     // Anything in here need not be OK at Design time in Visual Studio                 
}
Paulustrious
  • 609
  • 1
  • 11
  • 17
0

In you "partial class" of XAML, if you can see " [XamlCompilation(XamlCompilationOptions.Compile)]", just remove the line, and then try build again.

Jagger
  • 2,352
  • 2
  • 13
  • 12
0

If someone else comes here, I had inadvertently dragged my MainWindow.xaml file to a sub folder. Dragging it back fixed the problem.

Alan
  • 1,378
  • 2
  • 19
  • 24
0

Change the "Build only" option to "Intellisense only" in the error list window

Yerla
  • 1
0

During refactoring the C# namespace changed for certain classes. The xmlns name was also changed accordingly.

In one place however the xmlns was changed where it should not have been. e.g., code like this:

<OldNS:SomeControl ... />

was incorrectly changed to

<NewNS:SomeControl ... />

The control SomeControl therefore did not exist in the namespace indicated by the NewNS mapping.

Instead of flagging this as a specific error, for whatever reason I got the "object reference not set to an instance of an object" exception instead, with no clue as to the source.

Ultimately finding and fixing this mistake cleared the problem.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
-1

Interestingly enough, I do a Build --> Clean Solution and the designer loads...

Just sayin.

Popeye
  • 19
  • 2