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".

3
  • are you using any styles to the user control? Commented Mar 24, 2014 at 5:35
  • wat code you put in your constructor?
    – Savaratkar
    Commented Mar 24, 2014 at 6: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?? Commented Mar 24, 2014 at 11:38

1 Answer 1

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
}
1
  • 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
    Commented Dec 5, 2014 at 10:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.