DataContext in XAML gives: Object reference not set to an instance of an object

Topics: Prism v4 - WPF 4
Jul 31, 2014 at 6:52 PM
Hi,
I'm using XAML: ...
 <Window .....       xmlns:view="clr-namespace:SampleApp.ViewModel"
        mc:Ignorable="d"
        Title="Sample" Height="500" Width="700">
    <Window.DataContext>
        <view:Datamodel/> <!-- This gives the error Object reference not set to an instance of an object -->
    </Window.DataContext>
The line with <view:Datamodel/> gets red error indicators, but at runtime everything is ok.
Assumption: This is not really an error
Question: Is there a fix/workaround and still continue with the declarative assignment of the viewmodel?

Best regards
Bo
Aug 2, 2014 at 11:18 AM
Good Day,

In your ViewModel, are you using GetIsInDesignMode code which is throwing some exceptions ?

Something like :
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
  // Some Object reference not set which would be throwing an uncatch exception here.
}
Regards

Dimitri
Aug 2, 2014 at 11:58 AM
Dimitri,
nothing like that. Just creating some properties like ObservableCollections, Commands and some more data classes are created in CTOR.
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
  // Some Object reference not set which would be throwing an uncatch exception here.
}
Regards

Bo
Aug 3, 2014 at 1:18 PM
Edited Aug 3, 2014 at 1:19 PM
HI Bo,

I had a similar issue and after commenting out just about everything in my CTOR I was able to find my issue while de-commenting one functionality at a time.

Regards,

Dimitri
Aug 3, 2014 at 6:48 PM
Finally got it:
  • 1st try: Using devenv to debug devenv did not show up with any exception loading the view into the designer. Output window gave no indication of error but the red marks continued.
  • 2nd try: removed everything from CTOR an rebuild it line by line until I hit the mark!
Application.Current.MainWindow.Closing += (o, e) => { };
One should always use
Application.Current.Exit += (o, e) => { };
Solved it,
Thanks for contributing

Bo