问题
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:
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;
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/3304547/how-to-force-visual-studio-2010-to-ignore-a-wpf-xaml-declared-datacontext-at-des