How to resolve the "Could not create an instance of Type" error when "Reloading the designer" in Visual Studio 2008?

So, I recently started trying to implement the application I am developing using an MVVM model.

However, I ran into this annoying problem where when I have my main window’s XAML code including this line:

            <uc_treeview:PluginTreeViewControl Margin="0,0,0,29" MinWidth="240" />

My PluginTreeViewControl object looks as follows:

using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Input;
using LANDesk.HealthCheck.PluginOutput;
using LANDesk.HealthCheckViewer.LoadOnDemand.Sections;

namespace LANDesk.HealthCheckViewer.LoadOnDemand.PluginTreeView
{
    public partial class PluginTreeViewControl : UserControl
    {
        //readonly GroupViewModel mGroup;

        public PluginTreeViewControl()
        {
            InitializeComponent();

            Output o = new Output();
            OutputViewModel viewModel = new OutputViewModel(o.PluginGroups);
            base.DataContext = viewModel;
        }
    }
}

So I found that the lines after the InitializeComponent() function are causing my attempts to “Reload the designer” to fail. If I comment them out, the designer reloads. Of course, then if I have to uncomment them before compiling or debugging, and comment them again, when working in the Designer.

So after a while a thought came to me that maybe their is some type of “if” statement that would be true for the designer but not for runtime. So I researched and found this: DesignerProperties.GetIsInDesignMode Method

After reading about this, I changed my code in my Constructor to this:

    public PluginTreeViewControl()
    {
        InitializeComponent();

        // This "if" block is only for Visual Studio Designer
        if (DesignerProperties.GetIsInDesignMode(this))
        {
            return;
        }
        Output o = new Output();
        OutputViewModel viewModel = new OutputViewModel(o.PluginGroups);
        base.DataContext = viewModel;
    }

And wouldn’t you know it, I have solved the issue entirely. The Designer now reloads just fine (as it doesn’t seem to error) and at run time the “if” statement is always false so the lines I need always run.

Also, the overhead of an “if (DesignerProperties.GetIsInDesignMode(this))” in inconsequential. However, I attempted to remove this overhead in Release builds as follows:

    public PluginTreeViewControl()
    {
        InitializeComponent();

        // This "if" block is only for Visual Studio Designer
        #if DEBUG
        if (DesignerProperties.GetIsInDesignMode(this))
        {
            return;
        }
        #endif
        Output o = new Output();
        OutputViewModel viewModel = new OutputViewModel(o.PluginGroups);
        base.DataContext = viewModel;
    }

Now, I don’t have a problem with my Designer. This workaround makes me super happy!

Leave a Reply