1

I have already seen the below link

WPF, 'Object reference not set to an instance of an object' in Designer

My problem is similar but a little different. I am not setting any data context in XAML itself. I am creating my own user control and I am using that in another.

<usercontrols:MyControl1 x:Name="MyControl1"  Grid.Row="5"  Height="Auto" Width="Auto">

    </usercontrols:MyControl1>

This is the code I am using in second control to refer MyControl1. This generally does not throw any exception. But, When I specify some code in the constructer of MyControl1, the exception is coming. It also says "Cannot Create an Instance of MyControl1".

Community
  • 1
  • 1
sriharsha KB
  • 127
  • 1
  • 11
  • are you using any styles to the user control? – Sajeetharan Mar 24 '14 at 05:35
  • wat code you put in your constructor? – Savaratkar Mar 24 '14 at 06:49
  • Creating Instances of some other user controls .. Like _SampleCOntrol=new MyControl3(Param1); I am pretty sure that the Param1 will be null before initialization. Probably that is the issue. But why designer throws error?? I mean it could just ignore it and load control .. no?? – sriharsha KB Mar 24 '14 at 11:38

1 Answers1

3

Just add this line in MainPage.xaml.cs page

Use the static proeprty DesignerProperties.IsInDesignTool to determine if your code is currently being used in a designer tool.

InitializeComponent();
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
    //Code that throws the exception
}
samar
  • 5,021
  • 9
  • 47
  • 71
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • The Designer was firing my usercontrol loaded event. The code gets a reference to the window it is part of which causes an exception in design mode. Adding this check solved my problem thanks. – kenjara Dec 05 '14 at 10:09