How to force Visual Studio 2010 to ignore a WPF XAML declared DataContext at design time?
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开发者_Go百科 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?
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.
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;
}
}
精彩评论