Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Designer "Could not create an instance of type"

In my UI XAML I'm essentially inheriting from a class "BaseView" that contains functionality common to several forms, however this is preventing the designer from displaying the form: "Could not create instance of type BaseView". The code will compile and run, but it is frustrating not to be able to see the form in the Designer. Is there a better way? Thanks.

XAML:

<vw:BaseView 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vw="clr-namespace:ReviewClient"   
    x:Class="ReviewClient.MainPage"

...

like image 863
jchadhowell Avatar asked May 14 '09 04:05

jchadhowell


4 Answers

The problem was that the base class was defined as abstract. This caused the designer to fail. This problem is described in more detail in the comments section of Laurent Bugnion's blog: http://geekswithblogs.net/lbugnion/archive/2007/03/02/107747.aspx

like image 123
jchadhowell Avatar answered Oct 21 '22 19:10

jchadhowell


I found a very useful solution to this on : http://www.progware.org/Blog/post/WPF-Designer-Error-Could-not-create-an-instance-of-type.aspx.

This link explains how the WPF designer window runs the Constructor to display the UI in XAML and the remedy: adding the following snippet to any part of constructor code which might be giving error:

if(!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
   //code producing exception         
}

the function name is self explanatory. :) This link also provides solutions on debugging issues with XAML.

like image 40
angad.stjudes Avatar answered Oct 21 '22 19:10

angad.stjudes


Another possible cause, as we just found here, so I'm adding this answer for future users, is if the project is hosted on an untrusted source, such as a file server.

In that case, the designer wouldn't load the assembly and so gave the same "Could not create instance..." error. The solution would still build and debug OK.

like image 29
Andy Dent Avatar answered Oct 21 '22 18:10

Andy Dent


Another cause. My control class had a static field that was initialized from resources, like this:

 static Color s_ImgColor = (Color)TheApp.Resources["PhoneForegroundColor"];

That would throw a null reference exception in XAML editor, since the resources are not available in design mode. Were it not a color resource (say, a brush), this won't be a problem, but a typecast to value type throws up on a null reference.

like image 28
Seva Alekseyev Avatar answered Oct 21 '22 19:10

Seva Alekseyev