views:

78

answers:

2

Quite often I will set up WPF UserControl with a declarative DataContext:

<UserControl...>
    <UserControl.DataContext>
        <local:SomeModel x:Name="Model" />
    </UserControl.DataContext>
</UserControl>

When in design mode, Visual Studio will attempt to instantiate the DataContext. However, when the DataContext is pulling data from a configuration file, Visual Studio 2010 will throw an error such as:

Cannot create an instance of "SomeModel".

When the error is thrown, the design time experience is of little or no value. If I comment out the DataContext, then the Visual Studio 2010 design mode works as expected, sans DataContext.

Is there a way to have Visual Studio ignore the XAML declared DataContext at design time?

+1  A: 

Not sure I understand completely, but I use this extension method to detect when the designer is running my code:

public static class Extensions
{
    public static bool IsDesigner( this Process process )
    {
        if ( process.MainModule != null )
            return ( process.MainModule.ModuleName.Contains( "devenv.exe" ) );

        return false;
    }
}
David Lynch
The extension is a good work-around. I'd like to leave the question open for awhile to see if anyone has a pure XAML work-around. Thanks!
Metro Smurf
A: 

Override (or hide with 'new') you data context and make use of System.ComponentModel.DesignerProperties.GetIsInDesignMode() to return the appropriate context.

For bonus points, wrap your conditional break up in pre-processor directives and/or make use of judicious ConditionalAttribute() to ensure this extra noise doesn't make it out into a production environment.

SuperRetard