32

I'm getting an "Object reference not set to an instance of an object" error when I try to reload the Designer for my XAML UserControl. Visual Studio highlights the following line as being the problem:

<local:TemplateDetail Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3"
    Width="600" TemplateData="{Binding ElementName=cbo_templates,
                               Path=SelectedItem.Data, Mode=OneWay}"/>

TemplateDetail is another UserControl. When I view TemplateDetail, its Designer view loads just fine, so I don't think there's a problem there. There is a ComboBox in my XAML named cbo_templates that contains instances of my Template class, which has a Data property (hence SelectedItem.Data). However, if I remove .Data from the Path in the above XAML, I still get the "Object reference" error, so I don't think the problem is that I'm trying to access the Path property on null. Here's my ComboBox XAML just in case:

<ComboBox ItemsSource="{Binding Path=List}" Grid.Row="1" Grid.Column="3"
          VerticalAlignment="Center" x:Name="cbo_templates" Width="250"
          HorizontalAlignment="Left" DisplayMemberPath="Name"
          SelectedValuePath="Name" SelectedIndex="0"/>

Getting this error is a real problem because the Design view won't load, so I can't see what my UserControl looks like without running the app. Any idea what could be wrong? It builds fine and I don't see any binding problems in the Build Output.

Edit: here is the constructor code for both UserControls:

Constructor of UserControl with "Object reference" error:

InitializeComponent();
grd_templateList.DataContext = this; // refers to containing <Grid> in XAML

Constructor of UserControl I'm trying to embed, the one whose Design view loads okay:

InitializeComponent();
grd_templateDetail.DataContext = this; // refers to containing <Grid> in XAML

Edit: I tried putting an if (null != grd_templateList) check in the constructors before setting their DataContext properties, but that didn't help--still getting the "Object reference" error when reloading the Designer.

Edit: the List property that the ComboBox uses is a DependencyProperty. I have a default value set in the Register method:

public static readonly DependencyProperty ListProperty =
    DependencyProperty.Register(
        "List",
        typeof(List<Template>),
        typeof(TemplateList),
        new PropertyMetadata(
            new List<Template> { _defaultTemplate }
        )
    );

Even if I try to initialize List in the constructor for my UserControl, I still get the error when reloading the Designer. I don't think the problem is that List is null or SelectedItem.Data is a bad path.

Edit: okay, even just having this causes my Designer to not load, giving the "Object reference" error:

<local:TemplateDetail Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3"
                      TemplateData="{Binding}"/>

There is something it dislikes about the TemplateData property being bound, apparently.

Edit: to add to the mystery, I can view the Design view of my overall/main Window, which includes the UserControl whose Design view gives me the "Object reference" error. O_o

Sarah Vessels
  • 30,930
  • 33
  • 155
  • 222

9 Answers9

36

What Alex says is the way to go. But I think its a little confusing to understand what he is saying.

Assuming you have your project open in Visual Studio, open another Visual Studio instance and select Debug->Attach To Process. In the dialog which opens select

  • XDesProc.exe (which is the XAML UI Designer) for VS2012 and newer or
  • devenv.exe for older VS versions.

Then do "Reload Designer" for the user control and see the output in the second VS instance to check what exactly is the error.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
NVM
  • 5,442
  • 4
  • 41
  • 61
  • 2
    Thanks for the clarification. I tried this but nothing shows up in the second VS window (the one where I chose Attach to Process). I hit Reload Designer in my first VS window and it shows the same "Object reference" error in the Error List, but never pops over to the second VS window. Is there a way to set breakpoints in XAML? – Sarah Vessels Aug 20 '10 at 18:15
  • Actually I didnt see your xaml before. I think the problem is SelectedItem.Data. SelectedItem is null and you are referencing Data on it. Haha and now I read your text. Sorry!!! – NVM Aug 20 '10 at 18:18
  • @NVM: I dunno, even when I remove everything in the `Binding` so that it only says `Binding ElementName=cbo_templates`, I get the error. – Sarah Vessels Aug 20 '10 at 18:19
  • Ok on a couple of very rare ocassions I have found that when the second VS instance doesnt show anything. Restarting the project in VS magically solves the problem. This is a shot in the dark though. – NVM Aug 20 '10 at 18:23
  • 1
    @NVM: exiting VS, opening two instances, Attaching to the first, opening my project in the first, and then reloading the Designer still doesn't pop me over to the second VS or show anything at all in the second VS. :( I'm using VS 2010 if it matters. – Sarah Vessels Aug 20 '10 at 18:29
  • 1
    The Debug Output in the second VS instance says a bunch of stuff like 'devenv.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\assembly\GAC\EnvDTE90\9.0.0.0__b03f5f7f11d50a3a\EnvDTE90.dll', but nothing specific to my project that I see. – Sarah Vessels Aug 20 '10 at 18:31
  • I think this problem in itself is worth understanding. Anyway having a closer look at your code my instinct(experience) tells me new PropertyMetadata( new List – NVM Aug 20 '10 at 18:39
  • @NVM: I tried removing the `new PropertyMetadata` entirely, but that didn't help. I then tried just initializing a `new Template` in the `PropertyMetadata` constructor, but still the same problem. I'm looking around for how to debug design-time WPF. – Sarah Vessels Aug 20 '10 at 18:46
  • Note, a lot of the comments/answers want you to "Reload" the designer by task killing it, but that is completely unnecessary. Especially if you had attached to XDesProc.exe in a second VS instance. All you have to do is change a line of code in the XAML you are trying to debug and put the line back in. For example: if you have `d:DataContext="{d:DesignInstance Type=vm:MyViewModel, IsDesignTimeCreatable=True}"` Just remove that line and add it back in. This will cause the designer to attempt to recreate that object and should hit any breakpoints in your second VS instance. – Scyssion Apr 19 '17 at 15:18
12

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.

While you can find out the root of the problem with the help of other answers to this question, sometimes that is something you can't simply fix, you need it in your code exactly as you have it, but you don't want to see this error.

In this case, 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.

enter image description here

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Lirrik
  • 795
  • 11
  • 17
10

It's probably something in the constructor of your user controls. VS2008 WPF designer appears have some issues with this.

In a project we took over, we added:

if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
    return;
}

to the beginning of the constructor of the user controls where this happens to avoid that error.

Crispy
  • 5,557
  • 3
  • 30
  • 35
8

If your user control throws exception at design time, you can debug it. To do this, open Dll project with this user control in Visual Studio. Select another Visual Studio instance as executable for debugging. Start debugging. In the second (debugged) Visual Studio instance use your user control in the client XAML page. By this way, you can debug user control in design mode.

Alex F
  • 42,307
  • 41
  • 144
  • 212
  • By `select another Visual Studio instance as executable for debugging`, do you mean 'Attach to Process'? – Sarah Vessels Aug 20 '10 at 18:10
  • You can use Attach to Process, or open Project Properties, Debugging, executable for debugging session, and fill command line with command starting Visual Studio. Then execute "Start Debug" command. Another VS instance starts. In this instance, use user control on the client form or XAML page. – Alex F Aug 20 '10 at 18:26
  • NVM below explained how to go about doing this, but as I said in comments there, I can't get the second instance of VS 2010 to show any error messages about the "Object reference" error. – Sarah Vessels Aug 20 '10 at 19:44
  • Do you mean, that in standalone Visual Studio instance you can get exception, and in debugger instance it is not reproduced? Just do in debugged instance the same, as you do in standalone instance. You can also add Trace.WriteLine calls to the control code, testing for NULL different objects before using them. Catch this output with DbgView program. – Alex F Aug 21 '10 at 05:16
2

This thread is a little old, but I had a problem I just solved with its help, so I may be able to slightly clarify some points.

  1. Have your solution loaded in Visual Studio as usual.
  2. Open a 2nd instance of VS, menu debug/attach to process/select devenv. You should see nothing spectacular! In VS 2010, i just get "Disassembly cannot be displayed in run mode."
  3. Go back to your 1st instance, where your solution is opened. Load or reload the offending XAML file. If you have a problem (I had an exception on a user control, so I could not load that window), the debugger should point the offending code in the 2nd instance. in my case, it was very clear and obvious.

To prevent the offending code from running at design time, I used

    If System.ComponentModel.LicenseUsageMode.Runtime = 1 Then
        myObject = New ObjectDefinition
    End If

Works perfectly well.

BernardG
  • 1,956
  • 3
  • 17
  • 25
0

In Visual Studio 2015 for WPF:

  1. Hover with your mouse over the "Object reference not set to an instance of an object" in the Design view.
  2. Wait a (few) second(s) and you will see a popup
  3. Select "View Exception Details" (you will also see "View Code" and "Delete this element"
  4. This dialog will show you the exception and the StackTrace

Hope this helps.

If you do this on the XAML you will just see the exception but not the popup with "View Exception Details", thus you need to do it in the Designer/Design view.

juFo
  • 17,849
  • 10
  • 105
  • 142
0

I was able to solve the problem after giving a name to an object. It is VS2015, and my markup is different, but it could help somebody too:

<ResourceDictionary>
    <DataTemplate x:Key="ThisKeySolvesDesignersNullRef" 
                    DataType="local:MyViewModel">
        <local:MyControl/>
    </DataTemplate>
</ResourceDictionary>
astef
  • 8,575
  • 4
  • 56
  • 95
0

I was having this error today after editing a lot of XAML in my UWP code and I couldn't figure out what was wrong... but after some close inspection, I noticed this mistake I had made:

<Button Click="{Binding MyCommand}" />

I assigned my Command to the Click handler by mistake, and that resulted in a null reference exception... After changing Click to Command, the error went away.

XAML error reporting needs to be improved!

Shahin Dohan
  • 6,149
  • 3
  • 41
  • 58
0

I just had this problem with VS2022 (17.3.3). I tried to attach from another instance of VS but it never came up with the exception. I tried everything I could find such as handling the design case of the constructor and clearing out the .vs directory. Nothing helped. Finally I tried to run the application. The error didn't show when running. After running, the issue seems to be gone now. Even when I close and reopen the solution I don't see it anymore.

David Bowser
  • 107
  • 2
  • 10