Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

WPF Designer Error "Could not create an instance of type"

by Ioannis Panagopoulos

Suppose that in a WPF application there are some custom User Controls implemented.

During development in some windows that use the custom User Control you may find that the designer cannot load them and instead it gives the following error:

"Could not create an instance of type YOURCONTROLHERE"

This happens because the designer runs the constructor for the User Control whenever it needs to display it in design mode. Within the constructor something throws an exception. Sometimes this does not mean necessarily that the excepion will be thrown during runtime. So you need a way to allow the designer show the window but also not alter the code that runs correctly at runtime.

A way to solve this is to change your code as follows:

Original:

public UserControlConstructor()
{
    InitializeComponent();
    //Code that throws the exception
}

Change To:

public UserControlConstructor()
{
    InitializeComponent();
    if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
    {
        //Code that throws the exception
    }
}

The directive GetIsInDesignMode(this) does the trick of knowing whether the constructor is run in Design or Runtime mode.

 

 kick it on DotNetKicks.com Shout it

blog comments powered by Disqus
hire me